Your vector<string> userString
has size 0
, so the loop is never entered. You could start with a vector of a given size:
vector<string> userString(10);
string word;
string sentence;
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
cin >> word;
userString[i] = word;
sentence += userString[i] + " ";
}
although it is not clear why you need the vector at all:
string word;
string sentence;
for (int i = 0; i < 10; ++i)
{
cin >> word;
sentence += word + " ";
}
If you don't want to have a fixed limit on the number of input words, you can use std::getline
in a while
loop, checking against a certain input, e.g. "q"
:
while (std::getline(std::cin, word) && word != "q")
{
sentence += word + " ";
}
This will add words to sentence
until you type "q".
You may also which to use aggregate initialization from a braced initialization list for situations like these.
#include <vector>
using namespace std;
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub {
{"english", 10, 0},
{"math" , 20, 5}
};
}
Sometimes however, the members of a struct may not be so simple, so you must give the compiler a hand in deducing its types.
So extending on the above.
#include <vector>
using namespace std;
struct assessment {
int points;
int total;
float percentage;
};
struct subject {
string name;
int marks;
int credits;
vector<assessment> assessments;
};
int main() {
vector<subject> sub {
{"english", 10, 0, {
assessment{1,3,0.33f},
assessment{2,3,0.66f},
assessment{3,3,1.00f}
}},
{"math" , 20, 5, {
assessment{2,4,0.50f}
}}
};
}
Without the assessment
in the braced initializer the compiler will fail when attempting to deduce the type.
The above has been compiled and tested with gcc in c++17. It should however work from c++11 and onward. In c++20 we may see the designator syntax, my hope is that it will allow for for the following
{"english", 10, 0, .assessments{
{1,3,0.33f},
{2,3,0.66f},
{3,3,1.00f}
}},
source: http://en.cppreference.com/w/cpp/language/aggregate_initialization
These days (c++17
) it's easy:
auto const pusher([](auto& v) noexcept
{
return [&](auto&& ...e)
{
(
(
v.push_back(std::forward<decltype(e)>(e))
),
...
);
};
}
);
pusher(TestVector)(2, 5, 8, 11, 14);
So, your real question is: "How can JavaScript save to a local file?"
Take a look at http://www.tiddlywiki.com/
They save their HTML page locally after you have "changed" it internally.
[ UPDATE 2016.01.31 ]
TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.
TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(
[ END OF UPDATE
The trick is, you have to open the page as file:// not as http:// to be able to save locally.
The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.
-Jesse
This is what I did to extract the piece of the directory:
for path in file_list:
directories = path.rsplit('\\')
directories.reverse()
line_replace_add_directory = line_replace+directories[2]
Thank you for your help.
Copying an audio file to the sd card of the emulator and selecting it via media player as the default ringtone does indeed solve the problem.
This error occurs on an empty JSON file reading.
To avoid this error in NodeJS I'm checking the file's size:
const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;
sed cannot match \n because the trailing newline is removed before the line is put into the pattern space but can match \r, so you can convert \r\n (dos) to \n (unix) by removing \r
sed -i 's/\r//g' file
Warning: this will change the original file
However, you cannot change from unix EOL to dos or old mac (\r) by this. More readings here:
Converting to floating point and back seems like a huge waste of time at the CPU level.
Ian Nelson's solution:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
Can be simplified to:
int pageCount = (records - 1) / recordsPerPage + 1;
AFAICS, this doesn't have the overflow bug that Brandon DuRette pointed out, and because it only uses it once, you don't need to store the recordsPerPage specially if it comes from an expensive function to fetch the value from a config file or something.
I.e. this might be inefficient, if config.fetch_value used a database lookup or something:
int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');
This creates a variable you don't really need, which probably has (minor) memory implications and is just too much typing:
int recordsPerPage = config.fetch_value('records per page')
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
This is all one line, and only fetches the data once:
int pageCount = (records - 1) / config.fetch_value('records per page') + 1;
This should work:
background: -moz-linear-gradient(center top , #fad59f, #fa9907) repeat scroll 0 0 transparent;
/* For WebKit (Safari, Google Chrome etc) */
background: -webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
/* For Mozilla/Gecko (Firefox etc) */
background: -moz-linear-gradient(top, #fad59f, #fa9907);
/* For Internet Explorer 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
/* For Internet Explorer 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
Otherwise generate using the following link and get the code.
You can use this command which uses awk on git bash/unix to get the number of commits.
git shortlog -s -n | awk '/Author/ { print $1 }'
I found this presentation to be very helpfull.
How I Distribute Python applications on Windows - py2exe & InnoSetup
From the site:
There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.
There are several ways that you can transform data from multiple rows into columns.
PIVOT
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
See Demo.
columnnames
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;
See Demo.
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
select
max(case when columnname = 'FirstName' then value end) Firstname,
max(case when columnname = 'Amount' then value end) Amount,
max(case when columnname = 'PostalCode' then value end) PostalCode,
max(case when columnname = 'LastName' then value end) LastName,
max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See Demo.
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
The netdom.exe command line program can be used. This is available from the Windows XP Support Tools or Server 2003 Support Tools (both on the installation CD).
Usage guidelines here
I have found answers to my confusions.
There is a very important difference between the root
and the alias
directives. This difference exists in the way the path specified in the root
or the alias
is processed.
In case of the root
directive, full path is appended to the root including the location part, whereas in case of the alias
directive, only the portion of the path NOT including the location part is appended to the alias.
To illustrate:
Let's say we have the config
location /static/ {
root /var/www/app/static/;
autoindex off;
}
In this case the final path that Nginx will derive will be
/var/www/app/static/static
This is going to return 404
since there is no static/
within static/
This is because the location part is appended to the path specified in the root
. Hence, with root
, the correct way is
location /static/ {
root /var/www/app/;
autoindex off;
}
On the other hand, with alias
, the location part gets dropped. So for the config
location /static/ {
alias /var/www/app/static/;
autoindex off; ?
} |
pay attention to this trailing slash
the final path will correctly be formed as
/var/www/app/static
alias
directiveThere is no definitive guideline about whether a trailing slash is mandatory per Nginx documentation, but a common observation by people here and elsewhere seems to indicate that it is.
A few more places have discussed this, not conclusively though.
https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working
You can find standard sizes for everything in Google's style guide.
Here are the values they use for for buttons:
Buttons
English: Medium 14sp, all caps
Dense: Medium 15sp, all caps
Tall: Bold 15sp
The table and fields have the wrong encoding; however, you can convert them to UTF-8.
ALTER TABLE logtest CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE logtest DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE logtest CHANGE title title VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci;
You're likely not in the node directory. Try switching to the directory that you unpacked node to and try running the command there.
json_decode($json, true);
// the second param being true will return associative array. This one is easy.
Great answer by jheddings. I would like to improve it by allowing referencing of aggregated arrays or collections of objects, so that propertyName
could be property1.property2[X].property3
:
public static object GetPropertyValue(object srcobj, string propertyName)
{
if (srcobj == null)
return null;
object obj = srcobj;
// Split property name to parts (propertyName could be hierarchical, like obj.subobj.subobj.property
string[] propertyNameParts = propertyName.Split('.');
foreach (string propertyNamePart in propertyNameParts)
{
if (obj == null) return null;
// propertyNamePart could contain reference to specific
// element (by index) inside a collection
if (!propertyNamePart.Contains("["))
{
PropertyInfo pi = obj.GetType().GetProperty(propertyNamePart);
if (pi == null) return null;
obj = pi.GetValue(obj, null);
}
else
{ // propertyNamePart is areference to specific element
// (by index) inside a collection
// like AggregatedCollection[123]
// get collection name and element index
int indexStart = propertyNamePart.IndexOf("[")+1;
string collectionPropertyName = propertyNamePart.Substring(0, indexStart-1);
int collectionElementIndex = Int32.Parse(propertyNamePart.Substring(indexStart, propertyNamePart.Length-indexStart-1));
// get collection object
PropertyInfo pi = obj.GetType().GetProperty(collectionPropertyName);
if (pi == null) return null;
object unknownCollection = pi.GetValue(obj, null);
// try to process the collection as array
if (unknownCollection.GetType().IsArray)
{
object[] collectionAsArray = unknownCollection as object[];
obj = collectionAsArray[collectionElementIndex];
}
else
{
// try to process the collection as IList
System.Collections.IList collectionAsList = unknownCollection as System.Collections.IList;
if (collectionAsList != null)
{
obj = collectionAsList[collectionElementIndex];
}
else
{
// ??? Unsupported collection type
}
}
}
}
return obj;
}
There can be many possible reasons for this failure.
Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.
I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again
You can use Guava's Streams
.
concat(Stream<? extends T>... streams)
method, which will be very short with static imports:
Stream stream = concat(stream1, stream2, of(element));
I guess cross selection is not active anymore. We should use instead model selection. You can write it to run, from sklearn.model_selection import train_test_split
Thats it.
Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:
Using '@reboot' you can Run a command once, at startup.
Wrapping up:
run $ sudo crontab -e -u root
And add a line at the end of the file with your command as follows:
@reboot sudo searchd
You can also try Word Extractor tool. Word Extractor can be used with any file in your computer to separate the strings that contain human text / words from binary code (exe applications, DLLs).
Partially for the sake of summarization (excluding LINQ solution), here's two one-liners that address the int maxLength
caveat of allowing negative values and also the case of null string:
Substring
way (from Paul Ruane's answer):public static string Truncate(this string s, uint maxLength) =>
s?.Substring(0, Math.Min(s.Length, (int)maxLength));
Remove
way (from kbrimington's answer):public static string Truncate(this string s, uint maxLength) =>
s?.Length > maxLength ? s.Remove((int)maxLength) : s;
To make all lines taller, to look the same as the line with the superscript, define a larger line-height
for the entire paragraph
<p style='line-height:150%'>
or whatever value gives the effect you desire.
It may look strange, but that's how you described your requirements.
EDIT: In order to make all lines look the same when only one needs more vertical space than the others, ALL lines in the paragraph will have to be taller.
This, as I said, may not an attractive solution. Maybe something can be done with a span making just the text with the sub/superscript smaller, apart from that I don't believe what you want can be achieved. But I'd like to see someone else's solution.
EDIT2: Incidentally, I've tried a small html file containing
<html>
<head>
<title>line-height</title>
<style>
p {
line-height : 1.5em;
width : 25em;
}
</style>
</head>
<body>
<p>Mary had a little lamb, its fleece<sup>1</sup> was white as snow,
and everywhere that Mary went, the lamb<sub>2</sub> was sure to go.
</p>
</body>
</html>
And the lines are all the same height in FF3.0.14 and Konqueror (I can't speak for other browsers)
In my case it was an issue of the PHP version.
The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.
There are good answers here but If you like to have some interface for postgres database management, you can install pgAdmin on your local computer and connect to the remote machine using its IP and the postgres exposed port (by default 5432).
The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx()
methods of Date
, or on a library like moment.js.
<?php
// do something here
header("Location: http://example.com/thankyou.php");
?>
Add this to your xml:
android:listSelector="@android:color/transparent"
And for the problem this may work (I'm not sure and I don't know if there are better solutions):
You could apply a ColorStateList to your TextView.
If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.
I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID]
command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.
The simplest solution to the problem is to change your for loop statement :
Instead of using
for (i in **0**:n))
Use
for (i in **1**:n))
For the block element not occupy the whole line, set it's width to something small and the white-space:nowrap
label
{
width:10px;
display:block;
white-space:nowrap;
}
I suggest you to make this generic code :
$('a[href^="#"]').click(function(){
var the_id = $(this).attr("href");
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;});
You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide
If you have a single argument passed in the URL you can do it as follows
from flask import request
#url
http://10.1.1.1:5000/login/alex
from flask import request
@app.route('/login/<username>', methods=['GET'])
def login(username):
print(username)
In case you have multiple parameters:
#url
http://10.1.1.1:5000/login?username=alex&password=pw1
from flask import request
@app.route('/login', methods=['GET'])
def login():
username = request.args.get('username')
print(username)
password= request.args.get('password')
print(password)
What you were trying to do works in case of POST requests where parameters are passed as form parameters and do not appear in the URL. In case you are actually developing a login API, it is advisable you use POST request rather than GET and expose the data to the user.
In case of post request, it would work as follows:
#url
http://10.1.1.1:5000/login
HTML snippet:
<form action="http://10.1.1.1:5000/login" method="POST">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="password"><br>
<input type="submit" value="submit">
</form>
Route:
from flask import request
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
print(username)
password= request.form.get('password')
print(password)
You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.
I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.
To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.
edit
Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.
I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...
and it works in chrome whatever platform I am currently logged on to.
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
[].last; //=> undefined
A quick example of code for Application.Dispatcher.UnhandledException:
public App() {
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
// OR whatever you want like logging etc. MessageBox it's just example
// for quick debugging etc.
e.Handled = true;
}
I added this code in App.xaml.cs
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, String
is 0-indexed, i.e. the first character is at index 0
and the last character is at index length() - 1
.
So, assuming getSymbol()
returns a String
, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
Since you want to design an API using the REST architectural style you need to think about your use cases to decide which concepts are important enough to expose as resources. Should you decide to expose the status of a group as a sub-resource you could give it the following URI and implement support for both GET and PUT methods:
/groups/api/groups/{group id}/status
The downside of this approach over PATCH for modification is that you will not be able to make changes to more than one property of a group atomically and transactionally. If transactional changes are important then use PATCH.
If you do decide to expose the status as a sub-resource of a group it should be a link in the representation of the group. For example if the agent gets group 123 and accepts XML the response body could contain:
<group id="123">
<status>Active</status>
<link rel="/linkrels/groups/status" uri="/groups/api/groups/123/status"/>
...
</group>
A hyperlink is needed to fulfill the hypermedia as the engine of application state condition of the REST architectural style.
Using jQuery you can achieve this by doing
var cw = $('.child').width();
$('.child').css({'height':cw+'px'});
Here's a simple working solution:
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
.elem:hover {
-webkit-animation:spin 1.5s linear infinite;
-moz-animation:spin 1.5s linear infinite;
animation:spin 1.5s linear infinite;
}
gero's solution worked for me.
In Visual Studios 2012, take the following steps.
- Go to Solution Explorer
- Right click on your project
- Go to Properties
- Configuration Properties -> General
- Platform Toolset -> change to Windows7.1SDK
Another possibility would be the use of REGEXP_SUBSTR.
Just delete the old build from the device and reinstall the same. Because device.keystore is already exist in the device so just uninstall the build and reinstall the APK thats all..
Thanks
This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)
window.onbeforeunload = function () {
return "Are you sure?";
}
$(function () {
$('input[type="checkbox"]').click(function () {
window.onbeforeunload = function () { };
});
});
Here's a start.. Open to suggestions/improvements.
Server
public class ChatHub : Hub
{
public void SendChatMessage(string who, string message)
{
string name = Context.User.Identity.Name;
Clients.Group(name).addChatMessage(name, message);
Clients.Group("[email protected]").addChatMessage(name, message);
}
public override Task OnConnected()
{
string name = Context.User.Identity.Name;
Groups.Add(Context.ConnectionId, name);
return base.OnConnected();
}
}
JavaScript
(Notice how addChatMessage
and sendChatMessage
are also methods in the server code above)
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.addChatMessage = function (who, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(who).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#chat').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
Testing
You can replace the backslash character with, for example a pipe character, with sed.
sed -i -- 's/\\/|/g' filename.txt
The simplest solution is to select the second cell, and press =
. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1
) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.
To read up more on different options for referencing see - This Article.
Set
dgv.CurrentCell = null;
when user clicks on a blank part of the dgv.
Unbelievable, but on httpd 2.2 on centos 6.4 this works.
Export env vars in /etc/sysconfig/httpd
export mydocroot=/var/www/html
Then simply do this...
<VirtualHost *:80>
DocumentRoot ${mydocroot}
</VirtualHost>
Then finally....
service httpd restart;
You can add an event listener with 'ended' as first param
Like this :
<video src="video.ogv" id="myVideo">
video not supported
</video>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler(e) {
// What you want to do after the event
}
</script>
The best way to do it I think is:
if(val != true){
//do something
}
This will be true if val is false, NaN, or undefined.
To check the entire string and not allow empty strings, try
^[A-Za-z0-9_]+$
It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).
It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).
Here is the code I used:
CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY> INTEGER UNIQUE
PRIMARY KEY,
<MY_TABLE_SERIAL> TEXT DEFAULT (<MY_VALUE>)
NOT NULL
<THE_REST_COLUMNS>
);
I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.
I agree that this var formattedString = string.replace(/'/g, "\\'");
works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \
and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \
was the work around.
If the above problem is faced at Facebook login then you can use the below code in a parent activity of your fragment like:
Fragment fragment = getFragmentManager().findFragmentById(android.R.id.tabcontent);
fragment.onActivityResult(requestCode, resultCode, data);
Or:
Fragment fragment = getFragmentManager().findFragmentById("fragment id here");
fragment.onActivityResult(requestCode, resultCode, data);
And add the below call in your fragment...
callbackManager.onActivityResult(requestCode, resultCode, data);
$text="abc1234567890";
// truncate to 4 chars
echo substr(str_pad($text,4),0,4);
This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)
Much of the other answers provide shallow sizes - e.g. the size of a HashMap without any of the keys or values, which isn't likely what you want.
The jamm project uses the java.lang.instrumentation package above but walks the tree and so can give you the deep memory use.
new MemoryMeter().measureDeep(myHashMap);
https://github.com/jbellis/jamm
To use MemoryMeter, start the JVM with "-javaagent:/jamm.jar"
Mine is the console application (it should work for the windows application as well) and I had same problem. To solve it I used PlatformTarget as x64 as my System.Data.OracleClient.dll (64 bit file) is at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5. This will explicitly use 64 bit version of Oracle Client. This might help you if your solution works only on 64bit and if you are not using 32 bit dlls like dlls made in VB. I hope it will help you.
I had an idea about using a RAM drive. It turned out that for my projects it doesn't make that much of a difference after all. But then they are pretty small still. Try it! I'd be interested in hearing how much it helped.
GNU Parallel can presumably be used to improve many of the above answers by spreading the workload across multiple cores.
In the example below we send chunks of 500 numbers (--max-lines=500
) to bc
processes which are executed in parallel 4 at a time (-j 4
). The results are then aggregated by a final bc
.
time parallel --max-lines=500 -j 4 --pipe "paste -sd+ - | bc" < random_numbers | paste -sd+ - | bc
The optimal choice of work size and number of parallel processes depends on the machine and problem. Note that this solution only really shines when there's a large number of parallel processes with substantial work each.
style="?android:attr/android:progressBarStyleSmall"
to
style="?android:attr/progressBarStyleSmall"
When using NOT IN you should ensure that none of the values are NULL:
SELECT mac, creation_date
FROM logs
WHERE logs_type_id=11
AND mac NOT IN (
SELECT mac
FROM consols
WHERE mac IS NOT NULL -- add this
)
In windows I use a simple command in a batch file and I use a Scheduled Task to keep all the info in only one file. Be sure to choose another path to the result file, or You will have duplicate data.
type PathToOriginalFiles\*.Extension > AnotherPathToResultFile\NameOfTheResultFile.Extension
If you need to join lots of csv files, a good thing to do is to have the header in only one file with a name like 0header.csv, or other name, so that it will allways be the first file in list, and be sure to program all the other csv files to not contain an header.
An easy and elegant solution is to use _.isEqual
, which performs a deep comparison:
var a = {};
var b = {};
a.prop1 = 2;
a.prop2 = { prop3: 2 };
b.prop1 = 2;
b.prop2 = { prop3: 3 };
console.log(_.isEqual(a, b)); // returns false if different
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
However, this solution doesn't show which property is different.
Until I was really concerned about performance, I would use a function, that takes a base and returns its match:
char base_pair(char base)
{
switch(base) {
case 'T': return 'A';
... etc
default: // handle error
}
}
If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.
trunc(tran_date) = trunc(sysdate -1)
If you remove the connection string from the app.config
file, re-running the entity Data Model wizard will guide you to build a new connection.
Yes, since it's a dynamically type language ;)
Read this for reference: PEP 257
No regex, so no need for //.
this should work:
$str = str_replace("\\", '/', $str);
You need to escape "\" as well.
On Ubuntu I had to install php5 mysql
extension:
apt-get install php5-mysql
Getting name and subsetting based on Start, Contains, and Ends:
# from: https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html
# from: https://cmdlinetips.com/2019/04/how-to-select-columns-using-prefix-suffix-of-column-names-in-pandas/
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html
import pandas as pd
data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12]}
df = pd.DataFrame(data)
print("\n")
print("----------------------------------------")
colNames_contains = df.columns[df.columns.str.contains(pat = 'spike')].tolist()
print("Contains")
print(colNames_contains)
print("\n")
print("----------------------------------------")
colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist()
print("Starts")
print(colNames_starts)
print("\n")
print("----------------------------------------")
colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist()
print("Ends")
print(colNames_ends)
print("\n")
print("----------------------------------------")
df_subset_start = df.filter(regex='^spike',axis=1)
print("Starts")
print(df_subset_start)
print("\n")
print("----------------------------------------")
df_subset_contains = df.filter(regex='spike',axis=1)
print("Contains")
print(df_subset_contains)
print("\n")
print("----------------------------------------")
df_subset_ends = df.filter(regex='spike$',axis=1)
print("Ends")
print(df_subset_ends)
EDIT: This solution is not viable for newer versions of Bootstrap, where the navbar-inverse and navbar-static-top classes are not available.
Using MVC 5, the way I fixed mine, was to simply add my own Site.css, loaded after the others, with the following line:
body{padding: 0}
and I changed the code in the beginning of _Layout.cshtml, to be:
<body>
<div class="navbar navbar-inverse navbar-static-top">
<div class="container">
@if (User.Identity.IsAuthenticated) {
<div class="top-navbar">
Use this, it works 100% _your_videocode?rel=0&vq=hd1080"
Try this, it will work for sure.
When writing Rails migrations to convert a string column to an integer you'd usually say:
change_column :table_name, :column_name, :integer
However, PostgreSQL will complain:
PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.
The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).
$(".pushme").click(function () {
var button = $(this);
button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")
});
This ternary operator has an implicit return.
If the expression before ?
is true
it returns "DON'T PUSH ME"
, else returns "PUSH ME"
This if-else statement:
if (condition) { return A }
else { return B }
has the equivalent ternary expression:
condition ? A : B
It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.
If you are looking to manipulate the XML files you're probably best off using DOM XML
simple we are going to wait for 5 seconds for some event to happen (that would be indicated by done variable set to true somewhere else in the code) or when timeout expires that we will check every 100ms
var timeout=5000; //will wait for 5 seconds or untildone
var scope = this; //bind this to scope variable
(function() {
if (timeout<=0 || scope.done) //timeout expired or done
{
scope.callback();//some function to call after we are done
}
else
{
setTimeout(arguments.callee,100) //call itself again until done
timeout -= 100;
}
})();
I guess what you're looking for is pyquery:
pyquery: a jquery-like library for python.
An example of what you want may be like:
from pyquery import PyQuery
html = # Your HTML CODE
pq = PyQuery(html)
tag = pq('div#id') # or tag = pq('div.class')
print tag.text()
And it uses the same selectors as Firefox's or Chrome's inspect element. For example:
The inspected element selector is 'div#mw-head.noprint'. So in pyquery, you just need to pass this selector:
pq('div#mw-head.noprint')
Easy way to use for create dynamic header and cell in normal table :
<table width="100%" class="table">
<thead>
<tr>
<th ng-repeat="(header, value) in MyRecCollection[0]">{{header}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in MyRecCollection | filter:searchText">
<td ng-repeat="cell in row">{{cell}}</td>
</tr>
</tbody>
</table>
MyApp.controller('dataShow', function ($scope, $http) {
//$scope.gridheader = ['Name','City','Country']
$http.get('http://www.w3schools.com/website/Customers_MYSQL.php').success(function (data) {
$scope.MyRecCollection = data;
})
});
JSON Data :
[{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}, {
"Name": "Ernst Handel",
"City": "Graz",
"Country": "Austria"
}, {
"Name": "FISSA Fabrica Inter. Salchichas S.A.",
"City": "Madrid",
"Country": "Spain"
}, {
"Name": "Galería del gastrónomo",
"City": "Barcelona",
"Country": "Spain"
}, {
"Name": "Island Trading",
"City": "Cowes",
"Country": "UK"
}, {
"Name": "Königlich Essen",
"City": "Brandenburg",
"Country": "Germany"
}, {
"Name": "Laughing Bacchus Wine Cellars",
"City": "Vancouver",
"Country": "Canada"
}, {
"Name": "Magazzini Alimentari Riuniti",
"City": "Bergamo",
"Country": "Italy"
}, {
"Name": "North/South",
"City": "London",
"Country": "UK"
}, {
"Name": "Paris spécialités",
"City": "Paris",
"Country": "France"
}, {
"Name": "Rattlesnake Canyon Grocery",
"City": "Albuquerque",
"Country": "USA"
}, {
"Name": "Simons bistro",
"City": "København",
"Country": "Denmark"
}, {
"Name": "The Big Cheese",
"City": "Portland",
"Country": "USA"
}, {
"Name": "Vaffeljernet",
"City": "Århus",
"Country": "Denmark"
}, {
"Name": "Wolski Zajazd",
"City": "Warszawa",
"Country": "Poland"
}]
They are used in the linking stage. .a
files are statically linked, and .so
files are sort-of linked, so that the library is needed whenever you run the exe.
You can find where they are stored by looking at any of the lib directories... /usr/lib
and /lib
have most of them, and there is also the LIBRARY_PATH
environment variable.
It might be.. you have to identify it is tablet or phone by programmatically... First check device is phone or tablet
Determine if the device is a smartphone or tablet?
Then......
if(isTablet)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
This is known as a Shebang
:
http://en.wikipedia.org/wiki/Shebang_(Unix)
#!interpreter [optional-arg]
A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).
When a shell executes the script it will use the specified interpreter.
Example:
#!/bin/bash
# file: foo.sh
echo 1
$ chmod u+x foo.sh
$ ./foo.sh
1
Its Very simple
variable.GetType().Name
it will return your datatype of your variable
Even in 2009, it seems too many had a very limited idea of what designing for the WORLDWIDE web involved. In 2015, unless designing for a specific country, a blacklist is the only way to accommodate the vast number of characters that may be valid.
The characters to blacklist then need to be chosen according what is illegal for the purpose for which the data is required.
However, sometimes it pays to break down the requirements, and handle each separately. Here look-ahead is your friend. These are sections bounded by (?=)
for positive, and (?!)
for negative, and effectively become AND blocks, because when the block is processed, if not failed, the regex processor will begin at the start of the text with the next block. Effectively, each look-ahead block will be preceded by the ^
, and if its pattern is greedy, include up to the $
. Even the ancient VB6/VBA (Office) 5.5 regex engine supports look-ahead.
So, to build up a full regular expression, start with the look-ahead blocks, then add the blacklisted character block before the final $
.
For example, to limit the total numbers of characters, say between 3 and 15 inclusive, start with the positive look-ahead block (?=^.{3,15}$)
. Note that this needed its own ^
and $
to ensure that it covered all the text.
Now, while you might want to allow _ and -, you may not want to start or end with them, so add the two negative look-ahead blocks, (?!^[_-].+)
for starts, and (?!.+[_-]$)
for ends.
If you don't want multiple _
and -
, add a negative look-ahead block of (?!.*[_-]{2,})
. This will also exclude _-
and -_
sequences.
If there are no more look-ahead blocks, then add the blacklist block before the $
, such as [^<>[\]{\}|\\\/^~%# :;,$%?\0-\cZ]+
, where the \0-\cZ
excludes null and control characters, including NL (\n
) and CR (\r
). The final +
ensures that all the text is greedily included.
Within the Unicode domain, there may well be other code-points or blocks that need to be excluded as well, but certainly a lot less than all the blocks that would have to be included in a whitelist.
The whole regex of all of the above would then be
(?=^.{3,15}$)(?!^[_-].+)(?!.+[_-]$)(?!.*[_-]{2,})[^<>[\]{}|\\\/^~%# :;,$%?\0-\cZ]+$
which you can check out live on https://regex101.com/, for pcre (php), javascript and python regex engines. I don't know where the java regex fits in those, but you may need to modify the regex to cater for its idiosyncrasies.
If you want to include spaces, but not _
, just swap them every where in the regex.
The most useful application for this technique is for the pattern
attribute for HTML input
fields, where a single expression is required, returning a false for failure, thus making the field invalid, allowing input:invalid
css to highlight it, and stopping the form being submitted.
There you go: (a-zA-Z)
function codeToChar( number ) {
if ( number >= 0 && number <= 25 ) // a-z
number = number + 97;
else if ( number >= 26 && number <= 51 ) // A-Z
number = number + (65-26);
else
return false; // range error
return String.fromCharCode( number );
}
input: 0-51, or it will return false (range error);
OR:
var codeToChar = function() {
var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
return function( code ) {
return abc[code];
};
})();
returns undefined in case of range error. NOTE: the array will be created only once and because of closure it will be available for the the new codeToChar function. I guess it's even faster then the first method (it's just a lookup basically).
For url like https://myapp.com/user/666/read?age=23 use
import { combineLatest } from 'rxjs';
// ...
combineLatest( [this.route.paramMap, this.route.queryParamMap] )
.subscribe( ([pathParams, queryParams]) => {
let userId = pathParams.get('userId'); // =666
let age = queryParams.get('age'); // =23
// ...
})
In case when you use this.router.navigate([someUrl]);
and your query parameters are embedded in someUrl
string then angular encodes a URL and you get something like this https://myapp.com/user/666/read%3Fage%323 - and above solution will give wrong result (queryParams will be empty, and path params can be glued to last path param if it is on the path end). In this case change the way of navigation to this
this.router.navigateByUrl(someUrl);
The webbrowser
module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM
import webbrowser
webbrowser.open('http://google.co.kr', new=2)
Out of curiosity, I wanted to see how Value
performed against Value2
. After about 12 trials of similar processes, I could not see any significant differences in speed so I would always recommend using Value
. I used the below code to run some tests with various ranges.
If anyone sees anything contrary regarding performance, please post.
Sub Trial_RUN()
For t = 0 To 5
TestValueMethod (True)
TestValueMethod (False)
Next t
End Sub
Sub TestValueMethod(useValue2 As Boolean)
Dim beginTime As Date, aCell As Range, rngAddress As String, ResultsColumn As Long
ResultsColumn = 5
'have some values in your RngAddress. in my case i put =Rand() in the cells, and then set to values
rngAddress = "A2:A399999" 'I changed this around on my sets.
With ThisWorkbook.Sheets(1)
.Range(rngAddress).Offset(0, 1).ClearContents
beginTime = Now
For Each aCell In .Range(rngAddress).Cells
If useValue2 Then
aCell.Offset(0, 1).Value2 = aCell.Value2 + aCell.Offset(-1, 1).Value2
Else
aCell.Offset(0, 1).Value = aCell.Value + aCell.Offset(-1, 1).Value
End If
Next aCell
Dim Answer As String
If useValue2 Then Answer = " using Value2"
.Cells(Rows.Count, ResultsColumn).End(xlUp).Offset(1, 0) = DateDiff("S", beginTime, Now) & _
" seconds. For " & .Range(rngAddress).Cells.Count & " cells, at " & Now & Answer
End With
End Sub
I suggest to place invisible(opacity = 0) button on your imageview and then handle interaction on button.
You have an image or a favicon link of the style ="../"
somewhere, that if the "../" were valid, would go beyond the top of the site, like this:
Image:
http://example.com/Images/test.jpg
Page
http://example.com/Pages/test.aspx
Valid on that page: ../Images/test.jpg
Would throw an error: ../../Images/test.jpg
Your hack of decrementing the count at the end is exactly that -- a hack.
Far better to write your loop correctly in the first place, so it doesn't count the last line twice.
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
return 0;
}
Personally, I think in this case, C-style code is perfectly acceptable:
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textexample.txt", "r");
int ch;
while (EOF != (ch=getc(infile)))
if ('\n' == ch)
++number_of_lines;
printf("%u\n", number_of_lines);
return 0;
}
Edit: Of course, C++ will also let you do something a bit similar:
int main() {
std::ifstream myfile("textexample.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
}
The non-greedy ?
works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .
. You need to tell them explicitly that you want to match line-breaks too with .
For example,
<img\s.*?>
works fine!
Check the results here.
Also, read about how dot behaves in various regex flavours.
"SELECT Applicant.applicantId, Applicant.lastName, Applicant.firstName, Applicant.middleName, Applicant.status,Applicant.companyId, Company.name, Applicant.createDate FROM (Applicant INNER JOIN Company ON Applicant.companyId = Company.companyId) WHERE Applicant.createDate between '" +dateTimePicker1.Text.ToString() + "'and '"+dateTimePicker2.Text.ToString() +"'";
this is what i did!!
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
Replace @RestController
with @Controller
.
Duration in seconds using Python 2.7 and the YouTube API v3:
try:
dur = entry['contentDetails']['duration']
try:
minutes = int(dur[2:4]) * 60
except:
minutes = 0
try:
hours = int(dur[:2]) * 60 * 60
except:
hours = 0
secs = int(dur[5:7])
print hours, minutes, secs
video.duration = hours + minutes + secs
print video.duration
except Exception as e:
print "Couldnt extract time: %s" % e
pass
You could set content as data attribute and then use attribute selectors, as shown here:
/* Select every cell containing word "male" */
td[data-content="male"] {
color: red;
}
/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
color: blue;
}
/* Select every cell containing "4" */
td[data-content*="4"] {
color: green;
}
_x000D_
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-content="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
_x000D_
You can also use jQuery to easily set the data-content attributes:
$(function(){
$("td").each(function(){
var $this = $(this);
$this.attr("data-content", $this.text());
});
});
Here is how i increased the memory allocation of eclipse Juno:
I have a total of 4GB on my system and when im working on eclipse, i dont run any other heavy softwares along side it. So I allocated 2Gb.
The thing i noticed is that the difference between min and max values should be of 512. The next value should be let say 2048 min + 512 = 2560max
Here is the heap value inside eclipse after setting -Xms2048m -Xmx2560m
:
I looked at several solutions but all failed with scroll and select text being the biggest confusion. Instead of scrolling right I was closing boxes and such.
I just finished my implementation that does it all for me.
https://github.com/webdevelopers-eu/jquery-dna-gestures
It is MIT so do what you want - and yes, it is really simple - 800 bytes minified. You can check it out on my (under-development) site https://cyrex.tech - swiperight on touch-devices should dismiss popup windows.
I faced same issue in eclipse neon simple maven java project
But I add below details inside pom.xml file
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
After right click on project > maven > update project (checked force update)
Its resolve me to display error on project
Hope it's will helpful
Thansk
[Updated Dec 2020]: Tested and Included 5.0
version of Bootstrap.
I know this question is old. And the question did not mentioned which version of Bootstrap he was using. So i'll assume the answer to this question is resolved.
If any of you (like me) stumbled upon this question and looking for answer using current bootstrap 5.0 (2020) and 4.5 (2019) framework, then here's the solution.
Use d-flex justify-content-center
on your column div. This will center everything inside that column.
<div class="row">
<div class="col-4 d-flex justify-content-center">
// Image
</div>
</div>
If you want to align the text inside the col just use text-center
<div class="row">
<div class="col-4 text-center">
// text only
</div>
</div>
If you have text and image inside the column, you need to use d-flex
justify-content-center
and text-center
.
<div class="row">
<div class="col-4 d-flex justify-content-center text-center">
// for image and text
</div>
</div>
I have created a function in PHP language to get browser name, browser version, operating system (windows/linux etc.) along with device type (desktop / mobile / tablet).
function getBrowserInfo(){
$browserInfo = array('user_agent'=>'','browser'=>'','browser_version'=>'','os_platform'=>'','pattern'=>'', 'device'=>'');
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$ub = 'Unknown';
$version = "";
$platform = 'Unknown';
$deviceType='Desktop';
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$u_agent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($u_agent,0,4))){
$deviceType='Mobile';
}
if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10') {
$deviceType='Tablet';
}
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
$deviceType='Tablet';
}
//$detect = new Mobile_Detect();
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the user agent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'IE';
$ub = "MSIE";
} else if(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
} else if(preg_match('/Chrome/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent)))
{
$bname = 'Chrome';
$ub = "Chrome";
} else if(preg_match('/Safari/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent)))
{
$bname = 'Safari';
$ub = "Safari";
} else if(preg_match('/Opera/i',$u_agent) || preg_match('/OPR/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
} else if(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
} else if((isset($u_agent) && (strpos($u_agent, 'Trident') !== false || strpos($u_agent, 'MSIE') !== false)))
{
$bname = 'Internet Explorer';
$ub = 'Internet Explorer';
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
} else {
$version= @$matches['version'][1];
}
} else {
$version= $matches['version'][0];
}
// check if we have a number
if ($version==null || $version=="") {$version="?";}
return array(
'user_agent' => $u_agent,
'browser' => $bname,
'browser_version' => $version,
'os_platform' => $platform,
'pattern' => $pattern,
'device' => $deviceType
);
}
This solved my problem of browser detection, I hope, this will also help you. Thank you.
SELECT MIN(Date) AS Date FROM tbl_Employee /*To get First date Of Employee*/
export PATH="~/anaconda3/bin":$PATH
window.onload
- Called after all DOM, JS files, Images, Iframes, Extensions and others completely loaded. This is equal to $(window).load(function() {});
body onload=""
- Called once DOM loaded. This is equal to $(document).ready(function() {});
I think there's a simpler solution: Just use the DialogInterface
argument that is passed to the onClick
method.
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
See, for example, http://www.mkyong.com/android/android-alert-dialog-example.
Javascript redirection generated with php code:
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<script> window.location.assign('index.php'); </script>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
Php redirection only:
<?php
header("Location: index.php");
exit;
?>
Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)
not allowed characters in file/folder names
" * / : < > ? \ |
U may find this code helpful in such a case.
The below code removes all ":" and replaces them with "-"
//actualFileName = "qwerty:asdfg:zxcvb" say...
String[] tempFileNames;
String tempFileName ="";
String delimiter = ":";
tempFileNames = actualFileName.split(delimiter);
tempFileName = tempFileNames[0];
for (int j = 1; j < tempFileNames.length; j++){
tempFileName = tempFileName+" - "+tempFileNames[j];
}
File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
}
}
The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.
Log into the mosquitto
server's command line and type:
mosquitto
If mosquitto is installed the machine will return:
mosquitto version 1.4.8 (build date Wed, date of installation) starting
Using default config.
Opening ipv4 listen socket on port 1883
There are two types of progress bars called determinate progress bar (fixed duration) and indeterminate progress bar (unknown duration).
Drawables for both of types of progress bar can be customized by defining drawable as xml resource. You can find more information about progress bar styles and customization at http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples.
Customizing fixed or horizontal progress bar :
Below xml is a drawable resource for horizontal progress bar customization.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background"
android:gravity="center_vertical|fill_horizontal">
<shape android:shape="rectangle"
android:tint="?attr/colorControlNormal">
<corners android:radius="8dp"/>
<size android:height="20dp" />
<solid android:color="#90caf9" />
</shape>
</item>
<item android:id="@android:id/progress"
android:gravity="center_vertical|fill_horizontal">
<scale android:scaleWidth="100%">
<shape android:shape="rectangle"
android:tint="?attr/colorControlActivated">
<corners android:radius="8dp"/>
<size android:height="20dp" />
<solid android:color="#b9f6ca" />
</shape>
</scale>
</item>
</layer-list>
Customizing indeterminate progress bar
Below xml is a drawable resource for circular progress bar customization.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/progress"
android:top="16dp"
android:bottom="16dp">
<rotate
android:fromDegrees="45"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="315">
<shape android:shape="rectangle">
<size
android:width="80dp"
android:height="80dp" />
<stroke
android:width="6dp"
android:color="#b71c1c" />
</shape>
</rotate>
</item>
</layer-list>
Although Android can't find and connect to ad-hoc networks it sure can connect to Access Points. So as a work-around you can turn your Wireless Card into an Access Point using, for example, Connectify.
In my project, once it happened that someone manually entered the records without using sequence, hence I have to reset sequence value manually, for which I wrote below sql code snippet:
declare
max_db_value number(10,0);
cur_seq_value number(10,0);
counter number(10,0);
difference number(10,0);
dummy_number number(10);
begin
-- enter table name here
select max(id) into max_db_value from persons;
-- enter sequence name here
select last_number into cur_seq_value from user_sequences where sequence_name = 'SEQ_PERSONS';
difference := max_db_value - cur_seq_value;
for counter in 1..difference
loop
-- change sequence name here as well
select SEQ_PERSONS.nextval into dummy_number from dual;
end loop;
end;
Please note, the above code will work if the sequence is lagging.
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer
My problem was when converting .p12 certificate to .pem. I used:
openssl pkcs12 -in cert.p12 -out cert.pem
This converts and exports all certificates (CA + CLIENT) together with a private key into one file.
The problem was when I tried to verify if the hashes of certificate and key are matching by running:
// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5
// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5
This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/
I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.
So the solution was to export only CLIENT certificate together with private key:
openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``
Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5
HASHES MATCHED !!!
So I was able to make a curl request by running
curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com
without problems!!!
That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:
curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com
Well, for one thing your epression can be simplified:
$("#pDetails").attr("style")
since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.
If you just want to return the display value or something, use css():
$("#pDetails").css("display")
If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:
$("[style*='display: none']")
but if you just want to find things that are hidden, use this:
$(":hidden")
I always prefer pure SQL so :
SELECT 'ALTER TABLE [' + l.schema_n + '].['
+ l.table_name + '] ALTER COLUMN ['
+ l.column_name + '] ' + l.data_type + '('
+ Cast(l.new_max_length AS NVARCHAR(100))
+ ') COLLATE ' + l.dest_collation_name + ';',
l.schema_n,
l.table_name,
l.column_name,
l.data_type,
l.max_length,
l.collation_name
FROM (SELECT Row_number()
OVER (
ORDER BY c.column_id) AS row_id,
Schema_name(o.schema_id) schema_n,
ta.NAME table_name,
c.NAME column_name,
t.NAME data_type,
c.max_length,
CASE
WHEN c.max_length = -1
OR ( c.max_length > 4000 ) THEN 4000
ELSE c.max_length
END new_max_length,
c.column_id,
c.collation_name,
'French_CI_AS' dest_collation_name
FROM sys.columns c
INNER JOIN sys.tables ta
ON c.object_id = ta.object_id
INNER JOIN sys.objects o
ON c.object_id = o.object_id
JOIN sys.types t
ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN sys.index_columns ic
ON ic.object_id = c.object_id
AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i
ON ic.object_id = i.object_id
AND ic.index_id = i.index_id
WHERE 1 = 1
AND c.collation_name = 'SQL_Latin1_General_CP1_CI_AS'
--'French_CI_AS'-- ALTER DONE YET OLD VALUE :'SQL_Latin1_General_CP1_CI_AS'
) l
ORDER BY l.column_id;
if the package.json file in the project directory is missing then you can create it by npm init.
if the package.json file is already created in the project directory then there is a possibility that you are not running your project from the right path.
Use cd your-project-path
in the terminal and then run your project from there.
In a simular issue I had the desired dependency declared with scope provided. With this approach the transitive dependencies are fetched but are NOT included in the package phase, which is what you want. I also like this solution in terms of maintenance, because there is no pom, or custom pom as in whaley's solution, needed to maintain; you only need to provide the specific dependency in the container and be done
The If else statement needs to be wrapped in a .get or a .post to redirect. Such as
app.post('/login', function(req, res) {
});
or
app.get('/login', function(req, res) {
});
Yes. You can use reflection. Something like this:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
After trying many solution and lot of research I did to the following to make sure my localhost is accessible from other machine in same network. I didn't start my server with IPAddress as parameter to listen method as suggested by others in this question. I did the following to make sure my local node js server is accessible from other machine on same local network. My node server is running in Windows 10 machine.
Please see the attached screenshot:
After these changes, I am able to access my localhost using http://IPAddress:Port/ Thanks.
Something like this perhaps?
#/usr/bin/env ruby
if $stdin.tty?
ARGV.each do |file|
puts "do something with this file: #{file}"
end
else
$stdin.each_line do |line|
puts "do something with this line: #{line}"
end
end
Example:
> cat input.txt | ./myprog.rb
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb < input.txt
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb arg1 arg2 arg3
do something with this file: arg1
do something with this file: arg2
do something with this file: arg3
Easy as pie:
Open Eclipse and go to Help-> Software Updates-> Find and Install Select "Search for new features to install" and click "Next" Create a New Remote Site with the following details:
Name: PDT
URL: http://download.eclipse.org/tools/pdt/updates/4.0.1
Get the latest above mentioned URLfrom -
http://www.eclipse.org/pdt/index.html#download
Check the PDT box and click "Next" to start the installation
Hope it helps
If you know the aspect ratio for example, if your image is square you can set either the height
or the width
to fill the container and get the other to be set by the aspectRatio
property
Here is the style if you want the height
be set automatically:
{
width: '100%',
height: undefined,
aspectRatio: 1,
}
Note: height
must be undefined
Just another thing... Instead of System.out.println("Error Message Here")
, use System.err.println("Error Message Here")
. This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()
) in red.
NOTE: It also works when used with System.err.print("Error Message Here")
Choose one from, where :my_date
is a string input parameter of yyyy-MM-dd
format:
SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));
or
SELECT DATE_PART('year', CAST(:my_date AS DATE));
Better use CAST
than ::
as there may be conflicts with input parameters.
After countless hours of frustration I managed to get all working:
odbcinst.ini:
[FreeTDS]
Description = FreeTDS Driver v0.91
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
fileusage=1
dontdlclose=1
UsageCount=1
odbc.ini:
[test]
Driver = FreeTDS
Description = My Test Server
Trace = No
#TraceFile = /tmp/sql.log
ServerName = mssql
#Port = 1433
instance = SQLEXPRESS
Database = usedbname
TDS_Version = 4.2
FreeTDS.conf:
[mssql]
host = hostnameOrIP
instance = SQLEXPRESS
#Port = 1433
tds version = 4.2
First test connection (mssql is a section name from freetds.conf):
tsql -S mssql -U username -P password
You must see some settings but no errors and only a 1> prompt. Use quit to exit.
Then let's test DSN/FreeTDS (test is a section name from odbc.ini; -v means verbose):
isql -v test username password -v
You must see message Connected!
I used the logic in the replies by rampion and schnaader. I will summarise how I confirmed the results. I changed the numbers to binary and then used the XOR-operation. Alternatively, you can use the Hexadecimal tables: Click here!
Use the /i with xcopy and if the directory doesn't exist it will create the directory for you.
If I understand correctly, you have a vector containing variable names and would like loop through each name and sort your data frame by them. If so, this example should illustrate a solution for you. The primary issue in yours (the full example isn't complete so I"m not sure what else you may be missing) is that it should be order(Q1_R1000[,parameter[X]])
instead of order(Q1_R1000$parameter[X])
, since parameter is an external object that contains a variable name opposed to a direct column of your data frame (which when the $
would be appropriate).
set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
var2=round(rnorm(10)),
var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
# var1 var2 var3
#1 -1 2 1
#2 0 0 1
#3 -1 -1 0
#4 2 -2 -2
#5 0 1 1
#6 -1 0 0
#7 0 0 0
#8 1 1 -1
#9 1 1 0
#10 0 1 0
for(p in rev(param)){
dat <- dat[order(dat[,p]),]
}
dat
# var1 var2 var3
#3 -1 -1 0
#6 -1 0 0
#1 -1 2 1
#7 0 0 0
#2 0 0 1
#10 0 1 0
#5 0 1 1
#8 1 1 -1
#9 1 1 0
#4 2 -2 -2
For Xcode 7.3 and Swift 2.2.
let str = ""
If you want the number of visual characters:
str.characters.count
If you want the "16-bit code units within the string’s UTF-16 representation":
str.utf16.count
Most of the time, 1 is what you need.
When would you need 2? I've found a use case for 2:
let regex = try! NSRegularExpression(pattern:"",
options: NSRegularExpressionOptions.UseUnixLineSeparators)
let str = ""
let result = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.WithTransparentBounds,
range: NSMakeRange(0, str.utf16.count), withTemplate: "dog")
print(result) // dogdogdogdogdogdog
If you use 1, the result is incorrect:
let result = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.WithTransparentBounds,
range: NSMakeRange(0, str.characters.count), withTemplate: "dog")
print(result) // dogdogdog
This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
According to http://shouldiprefix.com/#appearance
Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.
I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/
In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable
the Optional stuff is really for return types not to be doing logic... but really neither here nor there.
I wanted to point out that java.util.Objects
has a nice method for this in a broad case, so you can do this:
cars.stream()
.filter(Objects::nonNull)
Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:
cars.stream()
.filter(car -> Objects.nonNull(car))
To partially answer the question at hand to return the list of car names that starts with "M"
:
cars.stream()
.filter(car -> Objects.nonNull(car))
.map(car -> car.getName())
.filter(carName -> Objects.nonNull(carName))
.filter(carName -> carName.startsWith("M"))
.collect(Collectors.toList());
Once you get used to the shorthand lambdas you could also do this:
cars.stream()
.filter(Objects::nonNull)
.map(Car::getName) // Assume the class name for car is Car
.filter(Objects::nonNull)
.filter(carName -> carName.startsWith("M"))
.collect(Collectors.toList());
Unfortunately once you .map(Car::getName)
you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:
cars.stream()
.filter(car -> Objects.nonNull(car))
.filter(car -> Objects.nonNull(car.getName()))
.filter(car -> car.getName().startsWith("M"))
.collect(Collectors.toList());
If you just want to tack something on by hand, then the sed
answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):
Using Perl:
perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt
N.B. while the >>
may look like an indication of redirection, it is just the file open mode, in this case "append".
Another way without JavaScript is to use <form autocomplete="off">
to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"
> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
It is not possible with the C99 standard library, unless you manually write a map from character constants to the corresponding ASCII int value.
Character constants in C like 'a'
are not guaranteed to be ASCII.
C99 only makes some guarantees about those constants, e.g. that digits be contiguous.
The word ASCII only appears on the C99 N1256 standard draft in footer notes, and footer note 173) says:
In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).
implying that ASCII is not the only possibility
Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.
YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}
You would put this inside a method for easy access. HTH
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
Just use Math.round()
double mkm = ((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt;
mkm= (double)(Math.round(mkm*100))/100;
DECLARE @StartDate DATE = '2017-09-13', @EndDate DATE = '2017-09-16'
SELECT date FROM ( SELECT DATE = DATEADD(DAY, rn - 1, @StartDate) FROM (
SELECT TOP (DATEDIFF(DAY, @StartDate, DATEADD(DAY,1,@EndDate)))
rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
ORDER BY s1.[object_id] ) AS x ) AS y
Result:
2017-09-13
2017-09-14
2017-09-15
2017-09-16
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}
If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.
Your original plan sounds fine to me. You'll probably find more browser quirks dealing with dynamically managing the <source>
elements, as indicated here by the W3 spec note:
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily[sic] complicated approach.
http://dev.w3.org/html5/spec/Overview.html#the-source-element
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
This might just help someone, in addition to what other answers have mentioned.
Clear the contents of AppData\Local\Microsoft\WebSiteCache
folder.
In my case I had VS 2015 pro update 3 and this is what helped me speed up VS.
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
It is an old question, but I am really surprised I don't see this trick here
Instead of using cd you can use
export PWD=the/path/you/want
No need to create subshells or use aliases.
Note that it is your responsibility to make sure the/path/you/want exists.
If you installed brew, cmd below will be helpful:
brew cask install java
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;
If you can manipulate one of the arrays, you can resize it before performing the copy:
T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);
Otherwise, you can make a new array
T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
T[] newArray = new T[array1.Length + array2.Length];
Array.Copy(array1, newArray, array1.Length);
Array.Copy(array2, 0, newArray, array1.Length, array2.Length);
By using JavaScript: document.getElementById("myBtn").click();
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
To extend @ChrisG's idea, a little, consider using process.MainWindowHandle and seeing if the window message loop is responding. Use p/invoke this Win32 api: SendMessageTimeout. From that link:
If the function succeeds, the return value is nonzero. SendMessageTimeout does not provide information about individual windows timing out if HWND_BROADCAST is used.
If the function fails or times out, the return value is 0. To get extended error information, call GetLastError. If GetLastError returns ERROR_TIMEOUT, then the function timed out.
i think the main things to remember about parsing csv is that it follows some simple rules:
a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns
have a read of this post to see what i am talking about
it's actually very easy to do once you have the hang of it and becomes very useful.
Style the left column with position: fixed
. (You'll presumably want to use top
and left
styles to control where exactly it occurs.)
If you're just searching for a string rather than a more complicated regular expression, you can use indexOf()
- but remember to lowercase both strings first because indexOf()
is case sensitive:
var string="Stackoverflow is the BEST";
var searchstring="best";
// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();
var result = lcString.indexOf(lcSearchString)>=0;
alert(result);
Or in a single line:
var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;
Procedure successful but any outpout
Error line1: Unexpected identifier
Here is the code:
SET SERVEROUTPUT ON
DECLARE
-- Curseurs
CURSOR c1 IS
SELECT RWID FROM J_EVT
WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));
-- Collections
TYPE tc1 IS TABLE OF c1%RWTYPE;
-- Variables de type record
rtc1 tc1;
vCpt NUMBER:=0;
BEGIN
OPEN c1;
LOOP
FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;
FORALL i IN 1..rtc1.COUNT
DELETE FROM J_EVT
WHERE RWID = rtc1(i).RWID;
COMMIT;
-- Nombres lus : 5025651
FOR i IN 1..rtc1.COUNT LOOP
vCpt := vCpt + SQL%BULK_RWCOUNT(i);
END LOOP;
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt));
END;
/
exit
Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.
https://gist.github.com/4689551
To use:
To copy (or move) a single file or a set of folders/files:
$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');
Delete a single file or all files and folders in a path:
$files = new Files();
$results = $files->delete('source/folder/optional-file.name');
Calculate the size of a single file or a set of files in a set of folders:
$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
will actually match any character, not only the literal dot between 'tar.bz2', for example
[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched
or anything that doesn't require escaping with '\'. The strict syntax should then be
[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched
or you can go even stricter and also include the previous dot in the regex:
[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched
aca definis los anchos
float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};
aca se los insertas a la tabla que tiene las columnas
table.setWidths(anchoDeColumnas);
You can use JSoup.
It's a very strong HTML parser
for java
A View in Oracle and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query
SELECT customerid, customername FROM customers WHERE countryid='US';
To create a view use the CREATE VIEW command as seen in this example
CREATE VIEW view_uscustomers
AS
SELECT customerid, customername FROM customers WHERE countryid='US';
This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this:
SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;
And Oracle will transform the query into this:
SELECT *
FROM (select customerid, customername from customers WHERE countryid='US')
WHERE customerid BETWEEN 100 AND 200
Benefits of using Views
You can find advanced topics in this article about "How to Create and Manage Views in Oracle."
In my case updating GIT helps - I had version 2.23 and with installing version 2.26.2.windows.1 problem disapears.
So if you are sure your SSH key is valid then (see @VonC answer):
And it should be ok.
you should use
getActivity.getSupportFragmentManager() like
//in my fragment
SupportMapFragment fm = (SupportMapFragment)
getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
I have also this issues but resolved after adding getActivity()
before getSupportFragmentManager
.
And for VB.net I found the following works:
Dim sec = New Newtonsoft.Json.Converters.StringEnumConverter()
sec.NamingStrategy() = New Serialization.CamelCaseNamingStrategy
Dim JSON_s As New JsonSerializer
JSON_s.Converters.Add(sec)
Dim jsonObject As JObject
jsonObject = JObject.FromObject(SomeObject, JSON_s)
Dim text = jsonObject.ToString
IO.File.WriteAllText(filePath, text)
var btn = document.querySelector('#twofuns');_x000D_
btn.addEventListener('click',method1);_x000D_
btn.addEventListener('click',method2);_x000D_
function method2(){_x000D_
console.log("Method 2");_x000D_
}_x000D_
function method1(){_x000D_
console.log("Method 1");_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>Pramod Kharade-Javascript</title>_x000D_
</head>_x000D_
<body>_x000D_
<button id="twofuns">Click Me!</button>_x000D_
</body>_x000D_
</html>
_x000D_
You can achieve/call one event with one or more methods.
are you looking for this ?
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
You can have multiple contexts for single database. It can be useful for example if your database contains multiple database schemas and you want to handle each of them as separate self contained area.
The problem is when you want to use code first to create your database - only single context in your application can do that. The trick for this is usually one additional context containing all your entities which is used only for database creation. Your real application contexts containing only subsets of your entities must have database initializer set to null.
There are other issues you will see when using multiple context types - for example shared entity types and their passing from one context to another, etc. Generally it is possible, it can make your design much cleaner and separate different functional areas but it has its costs in additional complexity.
I think the python memcached API is the prevalent tool, but I haven't used it myself and am not sure whether it supports the features you need.
This worked for me:
This could happen on any device, therefore in your app you will have to make sure to handle this error correctly. I reckon you give the user feedback why Login With Facebook failed and ask the user to check their Facebook settings on their device.
- (void)facebookSessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
// handle successful login here
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
if (error) {
// handle error here, for example by showing an alert to the user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Could not login with Facebook"
message:@"Facebook login failed. Please check your Facebook settings on your phone."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
break;
default:
break;
}
You simply cannot. DataFrames
, same as other distributed data structures, are not iterable and can be accessed using only dedicated higher order function and / or SQL methods.
You can of course collect
for row in df.rdd.collect():
do_something(row)
or convert toLocalIterator
for row in df.rdd.toLocalIterator():
do_something(row)
and iterate locally as shown above, but it beats all purpose of using Spark.
You either need to create an object of type Beta in the Alpha class or its method
Like you do here in the Main Beta cBeta = new Beta();
If you want to use the variable you create in your Main then you have to parse it to cAlpha as a parameter by making the Alpha constructor look like
public class Alpha
{
Beta localInstance;
public Alpha(Beta _beta)
{
localInstance = _beta;
}
public void DoSomethingAlpha()
{
localInstance.DoSomethingAlpha();
}
}
Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:
>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'
if there are multiple java processes and you wish to kill them with one command try the below command
kill -9 $(ps -ef | pgrep -f "java")
replace "java" with any process string identifier , to kill anything else.
When I face this problem I just edit the file and save it... works like charm
You must use newCachedThreadPool only when you have short-lived asynchronous tasks as stated in Javadoc, if you submit tasks which takes longer time to process, you will end up creating too many threads. You may hit 100% CPU if you submit long running tasks at faster rate to newCachedThreadPool (http://rashcoder.com/be-careful-while-using-executors-newcachedthreadpool/).
You could use lists()
:
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case
format, e.g Test
.
You could also use get()
:
test::where('id' ,'>' ,0)->get('id');
UPDATE: (For versions >= 5.2)
The lists()
method was deprecated in the new versions >= 5.2
, now you could use pluck()
method instead :
test::where('id' ,'>' ,0)->pluck('id')->toArray();
NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:
test::where('id' ,'>' ,0)->pluck('id');
Yes, you can.
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
YMMV.
It works because only Safari Mobile implements -webkit-touch-callout
: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout
Please note that @supports
does not work in IE. IE will skip both of the above @support
blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not
because of this.
What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.
Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling
but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".
sourceSets {
main {
res.srcDirs =
[
'src / main / res / layout / layout_1'
'src / main / res / layout / layout_2',
'src / main / res'
]
}
}
Simply goto MySql Console.
If using Wamp:
That's it. This set your root password to secret
In order to set user privilege to default one:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');
Works like a charm!
You can use order() to sort date data.
# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]
# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]
Hope this helps,
Link to my quora answer https://qr.ae/TWngCe
Thanks
It is possible to make a text-input multi-line by giving it the word-break: break-word;
attribute. (Only tested this in Chrome)
I recently got this message, too, after I switched the data center location of a web application sending through Google SMTP.
The URL that apparently Google means is: https://support.google.com/mail/answer/78754. At that link, one of the steps is to reset your password. Not coincidentally, I also received an email from google with a subject of "Suspicious sign in prevented" that instructed me to change my password.
After resetting my password, I was back to using Google SMTP as usual.
You can use clip-path
, as Stewartside and Sviatoslav Oleksiv mentioned. To make things easy, I created a sass mixin:
@mixin cut-corners ($left-top, $right-top: 0px, $right-bottom: 0px, $left-bottom: 0px) {
clip-path: polygon($left-top 0%, calc(100% - #{$right-top}) 0%, 100% $right-top, 100% calc(100% - #{$right-bottom}), calc(100% - #{$right-bottom}) 100%, $left-bottom 100%, 0% calc(100% - #{$left-bottom}), 0% $left-top);
}
.cut-corners {
@include cut-corners(10px, 0, 25px, 50px);
}
The pytz
module is one option, and there is another python-dateutil
, which although is also third party package, may already be available depending on your other dependencies and operating system.
I just wanted to include this methodology for reference- if you've already installed python-dateutil
for other purposes, you can use its tzinfo
instead of duplicating with pytz
import datetime
import dateutil.tz
# Get the UTC time with datetime.now:
utcdt = datetime.datetime.now(dateutil.tz.tzutc())
# Get the UTC time with datetime.utcnow:
utcdt = datetime.datetime.utcnow()
utcdt = utcdt.replace(tzinfo=dateutil.tz.tzutc())
# For fun- get the local time
localdt = datetime.datetime.now(dateutil.tz.tzlocal())
I tend to agree that calls to utcnow
should include the UTC timezone information. I suspect that this is not included because the native datetime library defaults to naive datetimes for cross compatibility.
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
Sometimes passing parameters in the main method causes this problem eg. public static void main(String[] args,int a)
. If you declare the variable outside the main method, it might help :)
Use the document.createElement function and then add it as a child of your select.
var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);
I was able to use the workspace setting that other people on this page have been asking for.
In Preferences, ?+P, search for python.pythonPath
in the search bar.
You should see something like:
// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
"python.pythonPath": "python"
Then click on the WORKSPACE SETTINGS tab on the right side of the window. This will make it so the setting is only applicable to the workspace you're in.
Afterwards, click on the pencil icon next to "python.pythonPath". This should copy the setting over the workspace settings.
Change the value to something like:
"python.pythonPath": "${workspaceFolder}/venv"
If this string is for presentation to the end user, you should use NSNumberFormatter
. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000
, but in Germany, that would be 10.000
.
Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.
create our test dict, see list and dict comprehensions:
>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}
Get the length of the value of a specific key:
>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3
Get a dict of the lengths of the values of each key:
>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2
Get the sum of the lengths of all values in the dict:
>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6
Just open a bug report with your OS vendor asking them to put the socket in /var/run so it automagically gets removed at reboot. It's a bug to keep this socket after an unclean reboot, /var/run is the spot for these kinds of files.
You can do inline ifs with
return y == 20 ? 1 : 2;
which will give you 1 if true and 2 if false.