got it from google, try to use this method
function getQuerystring2(key, default_)
{
if (default_==null)
{
default_="";
}
var search = unescape(location.search);
if (search == "")
{
return default_;
}
search = search.substr(1);
var params = search.split("&");
for (var i = 0; i < params.length; i++)
{
var pairs = params[i].split("=");
if(pairs[0] == key)
{
return pairs[1];
}
}
return default_;
}
As long as there are no identity columns you can just
INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
I tried @user2002993 great help but it one place it need to be a little edit so I edited and here what worked for me on Android Studio, emulator android 5.
Go to your adb folder right click on blank area and select "open command window here" or if you installed adb by adb-installer open cmd
and type these commands:
adb devices
It should show your emulator number and detail. Then followed command here:
adb shell
Now it should show you prompt #
su
mount -o rw,remount rootfs
chmod 777 /mnt/sdcard
exit
exit
Yeah double exit needed, now your prompt of adb shell is gone. Put a file in to your adb folder and give this command and see if it got fixed.
adb push "your file name like : 1.jpg" /sdcard/
or
adb push "your file name like : 1.jpg" /storage/sdcard/
Now in cmd it shoudl show you transfer time instead of creepy read-only thing
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.
I've just used the following command:
SET LIN[ESIZE] 200
(from http://ss64.com/ora/syntax-sqlplus-set.html).
EDIT: For clarity, valid commands are SET LIN 200
or SET LINESIZE 200
.
This works fine, but you have to ensure your console window is wide enough. If you're using SQL Plus direct from MS Windows Command Prompt, the console window will automatically wrap the line at whatever the "Screen Buffer Size Width" property is set to, regardless of any SQL Plus LINESIZE
specification.
As suggested by @simplyharsh, you can also configure individual columns to display set widths, using COLUMN col_name FORMAT Ax
(where x is the desired length, in characters) - this is useful if you have one or two extra large columns and you just wish to show a summary of their values in the console screen.
You can make a function to give you results.
# your list
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
453,435,324,34,456,56,567,65,34,435)
function1<-function(x){
if(x==value){return(1)}else{ return(0) }
}
# set your value here
value<-4
# make a vector which return 1 if it equal to your value, 0 else
vector<-sapply(numbers,function(x) function1(x))
sum(vector)
result: 2
public class JsonMapExample {
public static void main(String[] args) {
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Map<String, String> map = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {});
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
{phonetype=N95, cat=WP}
You can see this link it's helpful http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
Here are the steps that worked for me after logging into the box:
Locate MySQL configuration file:
$ mysql --help | grep -A 1 "Default options"
Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
On Ubuntu 16, the path is typically /etc/mysql/mysql.conf.d/mysqld.cnf
Change configuration file for bind-address:
If it exists, change the value as follows. If it doesn't exist, add it anywhere in the [mysqld] section.
bind-address = 0.0.0.0
Save your changes to the configuration file and restart the MySQL service.
service mysql restart
Create / Grant access to database user:
Connect to the MySQL database as the root user and run the following SQL commands:
mysql> CREATE USER 'username'@'%' IDENTIFIED BY 'password';
mysql> GRANT ALL PRIVILEGES ON mydb.* TO 'username'@'%';
Regarding the answer a bit up in this thread:
IsBadReadPtr(), IsBadWritePtr(), IsBadCodePtr(), IsBadStringPtr() for Windows.
My advice is to stay away from them, someone has already posted this one: http://blogs.msdn.com/oldnewthing/archive/2007/06/25/3507294.aspx
Another post on the same topic and by the same author (I think) is this one: http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx ("IsBadXxxPtr should really be called CrashProgramRandomly").
If the users of your API sends in bad data, let it crash. If the problem is that the data passed isn't used until later (and that makes it harder to find the cause), add a debug mode where the strings etc. are logged at entry. If they are bad it will be obvious (and probably crash). If it is happening way to often, it might be worth moving your API out of process and let them crash the API process instead of the main process.
In the Hibernate mapping file for the id
property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.
If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.
The above has a mix of correct answers. What worked for me for having the exact same errors are:
1) edit your bash config file
$ cd ~ && vim .bashrc
2) in your bash config file, make sure default editor is vim rather than vi (which causes the problem)
export EDITOR=vim
3) edit your vim config file
$cd ~ && vim .vimrc
4) make sure set backupcopy is yes in your .vimrc
set backupcopy=yes
5) restart terminal
6) now try crontab edit
$ crontab -e
10 * * * * echo "hello world"
You should see that it creates the crontab file correctly. If you exit vim (either ZZ or :wq) and list crontab with following command; you should see the new cron job. Hope this helps.
$ crontab -l
Majorly there are 3 ways of creating Objects-
Simplest one is using object literals.
const myObject = {}
Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.
So in that case it is better to use Factory or Constructor Functions.(anyone that you like)
Factory Functions are those functions that return an object.e.g-
function factoryFunc(exampleValue){
return{
exampleProperty: exampleValue
}
}
Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-
function constructorFunc(exampleValue){
this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);
What about the ansicolors library? You can simple do:
from colors import color, red, blue
# common colors
print(red('This is red'))
print(blue('This is blue'))
# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))
THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.
Attention :: people who don't understand the difference between a proposition let
, a constant const
and a variable var
should refrain themselves from commenting.
These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.
Suppose I need my variableName;
to carry an undefined
value, and therefore it has been declared in a manner such as var variableName;
which means it's already initialized; - How do I check if it's already declared?
Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?
We do it by using the most powerful JasvaScript operator, the in operator.:
"[variable||property]" in [context||root]
>> true||false
In times of AJAX peaking popularity I've written a method (later named) isNS() which is capable of determining if the namespace exists including deep tests for property names such as "Book1.chapter22.paragraph37" and a lot more.
But since it has been previously published and because of its great importance it deserves to be published in a separate thread I will not post it here but will provide keywords (javascript + isNS ) which will help you locate the source code, backed with all the necessary explanations.
For callback purposes I usually implement my own generic Runnable
with input parameter(s):
public interface Runnable<TResult> {
void run(TResult result);
}
Usage is simple:
myManager.doCallbackOperation(new Runnable<MyResult>() {
@Override
public void run(MyResult result) {
// do something with the result
}
});
In manager:
public void doCallbackOperation(Runnable<MyResult> runnable) {
new AsyncTask<Void, Void, MyResult>() {
@Override
protected MyResult doInBackground(Void... params) {
// do background operation
return new MyResult(); // return resulting object
}
@Override
protected void onPostExecute(MyResult result) {
// execute runnable passing the result when operation has finished
runnable.run(result);
}
}.execute();
}
There is no inherent ordering to a table. So, the row number itself is a meaningless metric.
However, you can get the row number of a result set by using the ROWNUM psuedocolumn or the ROW_NUMBER()
analytic function, which is more powerful.
As there is no ordering to a table both require an explicit ORDER BY clause in order to work.
select rownum, a.*
from ( select *
from student
where name like '%ram%'
order by branch
) a
or using the analytic query
select row_number() over ( order by branch ) as rnum, a.*
from student
where name like '%ram%'
Your syntax where name is like ...
is incorrect, there's no need for the IS, so I've removed it.
The ORDER BY here relies on a binary sort, so if a branch starts with anything other than B the results may be different, for instance b
is greater than B
.
I tried the most popular answers on this page but ran into an issue: the node_modules
directory in my Docker instance would get cached in the the named or unnamed mount point, and later would overwrite the node_modules
directory that was built as part of the Docker build process. Thus, new modules I added to package.json
would not show up in the Docker instance.
Fortunately I found this excellent page which explains what was going on and gives at least 3 ways to work around it: https://burnedikt.com/dockerized-node-development-and-mounting-node-volumes/
If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.
For example:
my_dict = {'key' : [1,2,3]}
import json
def dict_to_binary(the_dict):
str = json.dumps(the_dict)
binary = ' '.join(format(ord(letter), 'b') for letter in str)
return binary
def binary_to_dict(the_binary):
jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
d = json.loads(jsn)
return d
bin = dict_to_binary(my_dict)
print bin
dct = binary_to_dict(bin)
print dct
will give the output
1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101
{u'key': [1, 2, 3]}
The solution:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
works very well.
You have to convert the integer to a char(8) then a datetime. then wrap that in SELECT DATEPART(QUARTER, [date])
You will then have to convert the above to character and add on the '-' + year (also converted to char)
The arithmetic overflow above is caused by omitting the initial convert to a character type.
I would be inclined to abstract the conversion to date-time using views where possible and then use the quarter function and character conversion as and when required.
You could create your own class of type Quiz and then deserialize with strong type:
Example:
quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
new JsonSerializerSettings
{
Error = delegate(object sender1, ErrorEventArgs args1)
{
errors.Add(args1.ErrorContext.Error.Message);
args1.ErrorContext.Handled = true;
}
});
And you could also apply a schema validation.
My preferred centering method:
position: absolute;
margin: auto;
width: x%
A JSFiddle is here.
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
// UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
Hopefully, this reply will save beginners a lot of aggravation.
Could you not use typeof(object) to compare against
Try this code:
import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
}
}, 5000);
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.
NSArray *data = @[@"The String Value"];
if you need to send more than just 1 string value, you could also use
NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
then you can send it to the function like below
theFunction(data);
To your first question, you can't really do any query through YQL to get data for all companies. It's more oriented towards obtaining data for a smaller query. (I.e., it's not going to give you a full data dump of the whole Yahoo! Finance database.)
To your second question, here's how you can get started exploring the Yahoo! Finance tables in YQL:
finance
in the search fieldThen you can try some example queries like the following:
select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")
Update 2016-04-04: Here's a current screenshot showing the location of the Show Community Tables checkbox which must be clicked to see these finance tables:
to_frame():
Starting with the following Series, df:
email
[email protected] A
[email protected] B
[email protected] C
dtype: int64
I use to_frame to convert the series to DataFrame:
df = df.to_frame().reset_index()
email 0
0 [email protected] A
1 [email protected] B
2 [email protected] C
3 [email protected] D
Now all you need is to rename the column name and name the index column:
df = df.rename(columns= {0: 'list'})
df.index.name = 'index'
Your DataFrame is ready for further analysis.
Update: I just came across this link where the answers are surprisingly similar to mine here.
first: just use add method instead of replace method of FragmentTransaction class then you have to add secondFragment to stack by addToBackStack method
second :on back click you have to call popBackStackImmediate()
Fragment sourceFragment = new SourceFragment ();
final Fragment secondFragment = new SecondFragment();
final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.add(R.id.child_fragment_container, secondFragment );
ft.hide(sourceFragment );
ft.addToBackStack(NewsShow.class.getName());
ft.commit();
((SecondFragment)secondFragment).backFragmentInstanceClick = new SecondFragment.backFragmentNewsResult()
{
@Override
public void backFragmentNewsResult()
{
getChildFragmentManager().popBackStackImmediate();
}
};
I was curious about which method would be faster:
I found that depending on the size of the input data and the number of groups, the Distinct method can be a lot more performant. (as the number of groups tends towards the number of elements in the list, distinct runs faster).
Code runs in LinqPad!
void Main()
{
List<C> cs = new List<C>();
foreach(var i in Enumerable.Range(0,Int16.MaxValue*1000))
{
int modValue = Int16.MaxValue; //vary this value to see how the size of groups changes performance characteristics. Try 1, 5, 10, and very large numbers
int j = i%modValue;
cs.Add(new C{I = i, J = j});
}
cs.Count ().Dump("Size of input array");
TestGrouping(cs);
TestDistinct(cs);
}
public void TestGrouping(List<C> cs)
{
Stopwatch sw = Stopwatch.StartNew();
sw.Restart();
var groupedCount = cs.GroupBy (o => o.J).Select(s => s.First()).Count();
groupedCount.Dump("num groups");
sw.ElapsedMilliseconds.Dump("elapsed time for using grouping");
}
public void TestDistinct(List<C> cs)
{
Stopwatch sw = Stopwatch.StartNew();
var distinctCount = cs.Distinct(new CComparerOnJ()).Count ();
distinctCount.Dump("num distinct");
sw.ElapsedMilliseconds.Dump("elapsed time for using distinct");
}
public class C
{
public int I {get; set;}
public int J {get; set;}
}
public class CComparerOnJ : IEqualityComparer<C>
{
public bool Equals(C x, C y)
{
return x.J.Equals(y.J);
}
public int GetHashCode(C obj)
{
return obj.J.GetHashCode();
}
}
Here is a function that does the job quite well. I could not get the Best Answer above to work.
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
Then to access it, create the variable like so:
var results = $.getValues("url string");
@Reshma- In case you have not figured it yet, here are below things that I tried and it solved the same issue.
Make sure that NetworkCredentials you set are correct. For example in my case since it was office SMTP, user id had to be used in the NetworkCredential along with domain name and not actual email id.
You need to set "UseDefaultCredentials" to false first and then set Credentials. If you set "UseDefaultCredentials" after that it resets the NetworkCredential to null.
Hope it helps.
Below is an improvement over James Padolsey's solution:
1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example).
2) It's faster since it checks for a documentMode value before generating markup.
3) It's far more legible, especially to beginning JavaScript programmers.
Gist link: https://gist.github.com/julianshapiro/9098609
/*
- Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
- Behavior: For <IE8, we inject conditional comments until we detect a match.
- Results: In IE, the version is returned. In other browsers, false is returned.
- Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/
var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 0; i--) {
var div = document.createElement("div");
div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
if (div.getElementsByTagName("span").length) {
return i;
}
}
}
return undefined;
})();
Try This:
int positionOfJPG=url.IndexOf(".jpg");
string newString = url.Substring(18, url.Length - positionOfJPG);
Possibly the easiest way to make PHP perform a POST request is to use cURL, either as an extension or simply shelling out to another process. Here's a post sample:
// where are we posting to?
$url = 'http://foo.com/script.php';
// what post fields?
$fields = array(
'field1' => $field1,
'field2' => $field2,
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
Also check out Zend_Http set of classes in the Zend framework, which provides a pretty capable HTTP client written directly in PHP (no extensions required).
2014 EDIT - well, it's been a while since I wrote that. These days it's worth checking Guzzle which again can work with or without the curl extension.
A simple answer is to use @Html.TextboxFor but place it in a div that is hidden with style. Example: In View:
<div style="display:none">
@Html.TextboxFor(x=>x.CRN)
</div>
If you really want to use Xcode on linux you could get Virtual Box and install Hackintosh on a VM. Edit: Virtual Box Guest Additions is not supported with MacOS Movaje. You will want to use VMware
The CPP Section of the GCC Manual indicates that header files may be located in the following directories:
GCC looks in several different places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with #include in:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/g++-v3, first.
For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
Full validation example with javascript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Radio button: full validation example with javascript</title>
<script>
function send() {
var genders = document.getElementsByName("gender");
if (genders[0].checked == true) {
alert("Your gender is male");
} else if (genders[1].checked == true) {
alert("Your gender is female");
} else {
// no checked
var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
document.getElementById('msg').innerHTML = msg;
return false;
}
return true;
}
function reset_msg() {
document.getElementById('msg').innerHTML = '';
}
</script>
</head>
<body>
<form action="" method="POST">
<label>Gender:</label>
<br />
<input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
<br />
<input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
<br />
<div id="msg"></div>
<input type="submit" value="send>>" onclick="return send();" />
</form>
</body>
</html>
Regards,
Fernando
Most Previous answers were correct but here is the answer and example for Python 3.7. Yes, you can create an abstract class and method. Just as a reminder sometimes a class should define a method which logically belongs to a class, but that class cannot specify how to implement the method. For example, in the below Parents and Babies classes they both eat but the implementation will be different for each because babies and parents eat a different kind of food and the number of times they eat is different. So, eat method subclasses overrides AbstractClass.eat.
from abc import ABC, abstractmethod
class AbstractClass(ABC):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
def eat(self):
pass
class Parents(AbstractClass):
def eat(self):
return "eat solid food "+ str(self.value) + " times each day"
class Babies(AbstractClass):
def eat(self):
return "Milk only "+ str(self.value) + " times or more each day"
food = 3
mom = Parents(food)
print("moms ----------")
print(mom.eat())
infant = Babies(food)
print("infants ----------")
print(infant.eat())
OUTPUT:
moms ----------
eat solid food 3 times each day
infants ----------
Milk only 3 times or more each day
if the items are unique:
for x in list:
#code
if x == list[-1]:
#code
other options:
pos = -1
for x in list:
pos += 1
#code
if pos == len(list) - 1:
#code
for x in list:
#code
#code - e.g. print x
if len(list) > 0:
for x in list[:-1]
#code
for x in list[-1]:
#code
I disagree that you should never want to check an object's type in C++. If you can avoid it, I agree that you should. Saying you should NEVER do this under any circumstance is going too far though. You can do this in a great many languages, and it can make your life a lot easier. Howard Pinsley, for instance, showed us how in his post on C#.
I do a lot of work with the Qt Framework. In general, I model what I do after the way they do things (at least when working in their framework). The QObject class is the base class of all Qt objects. That class has the functions isWidgetType() and isWindowType() as a quick subclass check. So why not be able to check your own derived classes, which is comparable in it's nature? Here is a QObject spin off of some of these other posts:
class MyQObject : public QObject
{
public:
MyQObject( QObject *parent = 0 ) : QObject( parent ){}
~MyQObject(){}
static bool isThisType( const QObject *qObj )
{ return ( dynamic_cast<const MyQObject*>(qObj) != NULL ); }
};
And then when you are passing around a pointer to a QObject, you can check if it points to your derived class by calling the static member function:
if( MyQObject::isThisType( qObjPtr ) ) qDebug() << "This is a MyQObject!";
Sometimes isMinifyEnabled = false
may help (make sure you clean the project before launch)
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
I've found this page on their github repo, I'll just paste the content here.
There are two main approaches for serializing and restoring a model.
The first (recommended) saves and loads only the model parameters:
torch.save(the_model.state_dict(), PATH)
Then later:
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
The second saves and loads the entire model:
torch.save(the_model, PATH)
Then later:
the_model = torch.load(PATH)
However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.
The answers here are outdated. Now you can easily use a CSS3 transform without hardcoding a margin. This works on all elements, including elements with no width or dynamic width.
Horizontal center:
left: 50%;
transform: translateX(-50%);
Vertical center:
top: 50%;
transform: translateY(-50%);
Both horizontal and vertical:
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Compatibility is not an issue: http://caniuse.com/#feat=transforms2d
You can change the database name using MySQL interface.
Go to http://www.hostname.com/phpmyadmin
Go to database which you want to rename. Next, go to the operation tab. There you will find the input field to rename the database.
The main difference is GIF is patented and a bit more widely supported. PNG is an open specification and alpha transparency is not supported in IE6. Support was improved in IE7, but not completely fixed.
As far as file sizes go, GIF has a smaller default color pallet, so they tend to be smaller file sizes at first glance. PNG files have a larger default pallet, however you can shrink their color pallet so that, when you do, they result in a smaller file size than GIF. The issue again is that this feature isn't as supported in Internet Explorer.
Also, because PNGs can support alpha transparency, they're the only option if you want a variation of transparency other than binary transparency.
var regex = /\d+/g;_x000D_
var string = "you can enter 30%-20% maximum 500 choices";_x000D_
var matches = string.match(regex); // creates array from matches_x000D_
_x000D_
document.write(matches);
_x000D_
I just wanted to add a simplified version of dumbledad's answer, since it is the correct one.
Create custom_selector.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/unselected" android:state_pressed="true" />
<item android:drawable="@drawable/selected" />
</selector>
Create selected.xml shape in drawable folder
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
<solid android:color="@color/selected"/>
<padding />
<stroke android:color="#000" android:width="1dp"/>
<corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>
Create unselected.xml shape in drawable folder
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
<solid android:color="@color/unselected"/>
<padding />
<stroke android:color="#000" android:width="1dp"/>
<corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>
Add following colors for selected/unselected state in color.xml of values folder
<color name="selected">#a8cf45</color>
<color name="unselected">#ff8cae3b</color>
you can check complete solution from here
Your regex should work 'as-is'. Assuming that it is doing what you want it to.
wordA(\s*)wordB(?! wordc)
This means match wordA
followed by 0 or more spaces followed by wordB
, but do not match if followed by wordc
. Note the single space between ?!
and wordc
which means that wordA wordB wordc
will not match, but wordA wordB wordc
will.
Here are some example matches and the associated replacement output:
Note that all matches are replaced no matter how many spaces. There are a couple of other points: -
(?! wordc)
is a negative lookahead, so you wont match lines wordA wordB wordc
which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?!
to match the whitespace. You may want to be more precise and use (?!\swordc)
. If you want to match against more than one space before wordc you can use (?!\s*wordc)
for 0 or more spaces or (?!\s*+wordc)
for 1 or more spaces depending on what your intention is.
Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.
*
will match 0 or more spaces so it will match wordAwordB. You may want to consider +
if you want at least one space.
(\s*)
- the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s
.
Update based on comment
Hello the problem is not the expression but the HTML out put that are not considered as whitespace. it's a Joomla website.
Preserving your original regex you can use:
wordA((?:\s| )*)wordB(?!(?:\s| )wordc)
The only difference is that not the regex matches whitespace OR
. I replaced wordc
with \swordc
since that is more explicit. Note as I have already pointed out that the negative lookahead ?!
will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.
Example matches:
This code checks if two intervals overlap.
---------|---|
---|---| > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
-------|---|
---|---| > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
------|---|
---|---| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
---|--| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
----|---|
---|-----| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|-| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|--| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
---|---| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|---| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
-------|---| > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
--------|---| > FALSE
Algorithm:
x1 < y2
and
x2 > y1
example 12:00 - 12:30 is not overlapping with 12:30 13:00
Strongly recommend the excellent date-fns library. Fast, modular, immutable, works with standard dates.
import * as DateFns from 'date-fns';
const ordinalInt = DateFns.format(someInt, 'do');
See date-fns docs: https://date-fns.org/v2.0.0-alpha.9/docs/format
I suggest you to use AWS CLI. As it is very easy using command line and awscli
aws s3 cp SOURCE_DIR s3://DEST_BUCKET/ --recursive
or you can use sync by
aws s3 sync SOURCE_DIR s3://DEST_BUCKET/
Remember that you have to install aws cli and configure it by using your Access Key ID and Secrect Access Key ID
pip install --upgrade --user awscli
aws configure
The use
operator is for giving aliases to names of classes, interfaces or other namespaces. Most use
statements refer to a namespace or class that you'd like to shorten:
use My\Full\Namespace;
is equivalent to:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
If the use
operator is used with a class or interface name, it has the following uses:
// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;
// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;
The use
operator is not to be confused with autoloading. A class is autoloaded (negating the need for include
) by registering an autoloader (e.g. with spl_autoload_register
). You might want to read PSR-4 to see a suitable autoloader implementation.
Razz's solution would work for the .hide()
and .show()
methods but would not work for the .toggle()
method.
Depending upon the scenario, having a css class .inline_block { display: inline-block; }
and calling $(element).toggleClass('inline_block')
solves the problem for me.
All of the previous answers explain what the OP 'should' do. I am explaining what the .SelectedText
property is.
The .SelectedText
property is not the text in the combobox
. It is the text that is highlighted. It is the same as .SelectedText
property for a textbox
.
The following picture shows that the .SelectedText
property would be equal to "ort".
Be careful when using Convert.ToInt32()
on a char!
It will return the UTF-16 code of the character!
If you access the string only in a certain position using the [i]
indexing operator, it will return a char
and not a string
!
String input = "123678";
^
|
int indexOfSeven = 4;
int x = Convert.ToInt32(input[indexOfSeven]); // Returns 55
int x = Convert.ToInt32(input[indexOfSeven].toString()); // Returns 7
I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..
startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"
startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"
select just changes cardinality of the result table but project does change both degree of relation and cardinality.
.at-counter-box {
border: 2px solid #1ac6ff;
width: 150px;
height: 150px;
border-radius: 100px;
font-family: 'Oswald Sans', sans-serif;
color:#000;
}
.at-counter-box-content {
position: relative;
}
.at-counter-content span {
font-size: 40px;
font-weight: bold ;
text-align: center;
position: relative;
top: 55px;
}
To simulate an event, you could to use trigger
JQuery functionnality.
$('#foo').on('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
// to return valid days of month, according to month and year
int returnDaysofMonth(int month, int year) {
int daysInMonth;
boolean leapYear;
leapYear = checkLeap(year);
if (month == 4 || month == 6 || month == 9 || month == 11)
daysInMonth = 30;
else if (month == 2)
daysInMonth = (leapYear) ? 29 : 28;
else
daysInMonth = 31;
return daysInMonth;
}
// to check a year is leap or not
private boolean checkLeap(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Here is the Pakka codes for making the height of a division equal to another dynamically - M C Jain, Chartered Accountant -->
<script language="javascript">
function make_equal_heights()
{
if ((document.getElementById('div_A').offsetHeight) > (document.getElementById('div_B').offsetHeight) )
{
document.getElementById('div_B').style.height = (document.getElementById('div_A').offsetHeight) + "px";
}
else
{
document.getElementById('div_A').style.height = (document.getElementById('div_B').offsetHeight) + "px"
}
}
</script>
</head>
<body style="margin:50px;" onload="make_equal_heights()">
<div id="div_A" style="height:200px; width:150px; margin-top:22px;
background-color:lightblue;float:left;">DIVISION A</div><br>
<div id="div_B" style="height:150px; width:150px; margin-left:12px;
background-color: blue; float:left; ">DIVISION B</div>
</body>
</html>
This was the first result on google, when I was looking how to rename a user, so:
ALTER USER <username> WITH PASSWORD '<new_password>'; -- change password
ALTER USER <old_username> RENAME TO <new_username>; -- rename user
A couple of other commands helpful for user management:
CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;
Move user to another group
ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;
Cong Ma does a good job of explaining what __getitem__
is used for - but I want to give you an example which might be useful.
Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :
Without using __getitem__
we would have a class like this :
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def occupy(self, floor_number, data):
self._floors[floor_number] = data
def get_floor_data(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )
We could however use __getitem__
(and its counterpart __setitem__
) to make the usage of the Building class 'nicer'.
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def __setitem__(self, floor_number, data):
self._floors[floor_number] = data
def __getitem__(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )
Whether you use __setitem__
like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.
Just to generalize Rob's answer a little, if you're not doing it on output, you can still use the same interface with sprintf()
.
I think there is another way to do it, though. You can try ceil()
and floor()
to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil()
and floor()
only work on double
s though.
EDIT: Also, for floats, you can use truncf()
to truncate floats. The same +0.5 trick should work to do accurate rounding.
I'm happy to report that since this question was asked, now there is a satisfactory answer! Take a look at this terrific package:
https://github.com/mysqludf/lib_mysqludf_preg
Sample SQL:
SELECT PREG_REPLACE('/(.*?)(fox)/' , 'dog' , 'the quick brown fox' ) AS demo;
I found the package from this blog post as linked on this question.
You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.
The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:
The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)
Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.
To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).
See the following for more discussion:
How do I properly clean up Excel interop objects?
To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).
A cleaner way to handle this is to query the spreadsheet using ADO:
If you are using Spring Framework, you can use Spring TagLib and SpEL:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
---
<spring:eval var="containsValue" expression="mylist.contains(myValue)" />
<c:if test="${containsValue}">style='display:none;'</c:if>
document.getElementById("fName").style.borderColor="";
is all you need to change the border color back.
To change the border size, use element.style.borderWidth = "1px"
.
You need to set the parent element to 100%
as well
html, body {
height: 100%;
}
Demo (Changed the background
for demo purpose)
Also, when you want to cover entire screen, seems like you want to dim
, so in this case, you need to use position: fixed;
#dimScreen {
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0;
left: 0;
z-index: 100; /* Just to keep it at the very top */
}
If that's the case, than you don't need html, body {height: 100%;}
You could try:
Hello! Here is some code:_x000D_
_x000D_
<xmp>_x000D_
<div id="hello">_x000D_
_x000D_
</div>_x000D_
</xmp>
_x000D_
The shortcut to comment out or uncomment the selected text or current line:
Alternatively, use the menu: Edit > Comment
For the block comment you may want to use:
In addition to @csgillespie's answer, segments
is also vectorised to help with this sort of thing:
plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)
You can use $.ajax call to get the value and then put it in the div you want to. One thing you must know is you cannot receive JSON Data. You have to use JSONP.
Code would be like this:
function CallURL() {
$.ajax({
url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan',
type: "GET",
dataType: "jsonp",
async: false,
success: function(msg) {
JsonpCallback(msg);
},
error: function() {
ErrorFunction();
}
});
}
function JsonpCallback(json) {
document.getElementById('summary').innerHTML = json.result;
}
Bootstrap4:
Comes with .no-gutters
out of the box.
source: https://github.com/twbs/bootstrap/pull/21211/files
Bootstrap3:
Requires custom CSS.
Stylesheet:
.row.no-gutters {
margin-right: 0;
margin-left: 0;
& > [class^="col-"],
& > [class*=" col-"] {
padding-right: 0;
padding-left: 0;
}
}
Then to use:
<div class="row no-gutters">
<div class="col-xs-4">...</div>
<div class="col-xs-4">...</div>
<div class="col-xs-4">...</div>
</div>
It will:
The solution is using of the following JVM argument:
-Dlog4j.configuration={path to file}
If the file is NOT in the classpath (in WEB-INF/classes
in case of Tomcat) but somewhere on you disk, use file:
, like
-Dlog4j.configuration=file:C:\Users\me\log4j.xml
More information and examples here: http://logging.apache.org/log4j/1.2/manual.html
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
Hmm, I see that Process Explorer can do it, although its graphs are not too convenient. Still looking for alternative / better ways to do it.
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
You can do this even shorter by replacing echo
with <?= code ?>
<?=(empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />'?>
This is useful especially when you want to determine, inside a navbar, whether the menu option should be displayed as already visited (clicked) or not:
<li<?=($basename=='index.php' ? ' class="active"' : '')?>><a href="index.php">Home</a></li>
This works perfectly for me try this just put ?rel=0&autoplay=1 in the end of link
<iframe width="631" height="466" src="https://www.youtube.com/embed/UUdMixCYeTA?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
I got this error. I was using interfaces in my constructor and my dependency resolver wasn't able to resolve, when i registered it then the error went away.
If you do not have the pandas and sqlalchemy libraries, import using pip
pip install pandas
pip install sqlalchemy
We can use pandas and sqlalchemy to directly insert into the database
import csv
import pandas as pd
from sqlalchemy import create_engine, types
engine = create_engine('mysql://root:*Enter password here*@localhost/*Enter Databse name here*') # enter your password and database names here
df = pd.read_csv("Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('Table_name',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name
The easiest way is to use LINQ's Union
method:
var aUb = A.Union(B).ToList();
After
brew uninstall node
I had to know which node
which node
then remove that
rm -rf /usr/local/bin/node
You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.
In my somewhat checkered experience, applying -O3
to an entire program almost always makes it slower (relative to -O2
), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2
relative to -Os
!
The intended use pattern for -O3
is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3
optimizations to hot functions -- effectively automating this process.
Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.
Press CTRL+Shift+A to open up the Actions menu. Type Maven
and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line
Try this:
Update users
Set username = 'Jack', password='123'
Where ID = '1'
Or if you're actually trying to insert:
Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
you mentioned "entire line" , so i assumed mystring is the entire line.
if "token" in mystring:
print(mystring)
however if you want to just get "token qwerty",
>>> mystring="""
... qwertyuiop
... asdfghjkl
...
... zxcvbnm
... token qwerty
...
... asdfghjklñ
... """
>>> for item in mystring.split("\n"):
... if "token" in item:
... print (item.strip())
...
token qwerty
Ran a benchmark, and it turns out the fastest way of getting a real integer (using all the available methods) is
$foo = (int)+"12.345";
Just using
$foo = +"12.345";
returns a float.
Try the following code will help you to Launch an application from your application
Note: Replace the name fantacy with actual application name
NSString *mystr=[[NSString alloc] initWithFormat:@"fantacy://location?id=1"];
NSURL *myurl=[[NSURL alloc] initWithString:mystr];
[[UIApplication sharedApplication] openURL:myurl];
May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?
I got exactly the same error in Windows 8 while trying to export decision tree digraph using tree.export_graphviz! Then I installed GraphViz from this link. And then I followed the below steps which resolved my issue:
Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.
I get into this situation most of the times so normally i used to follow the step of setting the swap memory.
But now i found a simple alternate trick which worked for me.
Run
composer update --no-dev
Other than composer update
I faced the same problem and struggled for an hour to get pass through by reading the documents and the other issues reported in Stack Overflow but I didn't find any answer to it. So, here is the guide to successfully run the phonegap/cordova in Windows Machine.
npm install -g phonegap
(in case of phonegap installation) or run the command npm install -g cordova
(in case of Cordova installation).As the installation gets completed you can notice this:
C:\Users\binaryuser\AppData\Roaming\npm\cordova -> C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova\bin\cordova [email protected] C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova +-- [email protected] +-- [email protected] +-- [email protected] +-- [email protected] +-- [email protected] +-- [email protected] ([email protected]) +-- [email protected] ([email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
Notice the above line you can see the path were the file is mentioned. Copy that path. In my case it is C:\Users\binaryuser\AppData\Roaming\npm\cordova
so use cd C:\Users\binaryuser\AppData\Roaming\npm\
and type cordova
. There it is, it finally works.
-g
key value isn't working you have set the Environment Variables path:
Computer
and choose Properties
.Advanced system settings
on the left.Environment Variables
under the Advanced
tab.PATH
variable and click Edit
.OK
.type in Windows cmd.exe
cd %userprofile%\.android
dir
copy adbkey.pub adb_keys
dir
copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.
from: How to solve ADB device unauthorized in Android ADB host device?
now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
In your code j is Already json data and j['places'] is list not dict.
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
for each in j['places']:
print each['latitude']
There is an assembly instruction called BSWAP that will do the swap for you, extremely fast. You can read about it here.
Visual Studio, or more precisely the Visual C++ runtime library, has platform intrinsics for this, called _byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64()
. Similar should exist for other platforms, but I'm not aware of what they would be called.
If checkout master
was the last thing you did, then the reflog entry HEAD@{1}
will contain your commits (otherwise use git reflog
or git log -p
to find them). Use git merge HEAD@{1}
to fast forward them into master.
EDIT:
As noted in the comments, Git Ready has a great article on this.
git reflog
and git reflog --all
will give you the commit hashes of the mis-placed commits.
Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
Wrap the value passed in different classes that might be helpful doing the trick, check below for more real example:
class Ref<T>{
T s;
public void set(T value){
s = value;
}
public T get(){
return s;
}
public Ref(T value) {
s = value;
}
}
class Out<T>{
T s;
public void set(T value){
s = value;
}
public T get(){
return s;
}
public Out() {
}
}
public static void doAndChangeRefs (Ref<String> str, Ref<Integer> i, Out<String> str2){
//refs passed .. set value
str.set("def");
i.set(10);
//out param passed as null .. instantiate and set
str2 = new Out<String>();
str2.set("hello world");
}
public static void main(String args[]) {
Ref<Integer> iRef = new Ref<Integer>(11);
Out<String> strOut = null;
doAndChangeRefs(new Ref<String>("test"), iRef, strOut);
System.out.println(iRef.get());
System.out.println(strOut.get());
}
As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:
int main() {
std::map<std::string, std::map<std::string, std::string>> m {
{"name1", {{"value1", "data1"}, {"value2", "data2"}}},
{"name2", {{"value1", "data1"}, {"value2", "data2"}}},
{"name3", {{"value1", "data1"}, {"value2", "data2"}}}
};
for (const auto& [k1, v1] : m)
for (const auto& [k2, v2] : v1)
std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;
return 0;
}
Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.
Note 2: If you want to modify the map m
within the loops, you have to remove the const
keywords.
As addition of good answers, You don't have to use [FromForm]
to get form data in controller. Framework automatically convert form data to model as you wish. You can implement like following.
[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
{
//...
}
Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)
For something reusable:
template<template <typename> class P = std::less >
struct compare_pair_second {
template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {
return P<T2>()(left.second, right.second);
}
};
You can use it as
std::sort(foo.begin(), foo.end(), compare_pair_second<>());
or
std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());
If there is necessity for the user to move away from the field, we can use "onBlur" instead of Onchange in Javascript
<TextField id="outlined-basic" variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />
If that is not necessary setting timer would be the good option.
See for example Angular 2 - Implementation of shared services
@Injectable()
export class MyGlobals {
readonly myConfigValue:string = 'abc';
}
@NgModule({
providers: [MyGlobals],
...
})
class MyComponent {
constructor(private myGlobals:MyGlobals) {
console.log(myGlobals.myConfigValue);
}
}
or provide individual values
@NgModule({
providers: [{provide: 'myConfigValue', useValue: 'abc'}],
...
})
class MyComponent {
constructor(@Inject('myConfigValue') private myConfigValue:string) {
console.log(myConfigValue);
}
}
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
router.navigate['/path']
will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page
If you made an account using google/ other oauth, then you need to set a bitbucket password for your account first. The URL for that is : https://bitbucket.org/account/user// or look for Bitbucket settings under the menu.
Then can login from git (I tried via command line). I use the built in manager for credentials :
credential.helper=manager
Now, after I set the password on the bitbucket site (email verified too), and tried to push again, it prompted me for the password, then pushed the code.
Menu location image on bitbucket web page -> http://ctrlv.in/747291 as of May 2016.
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
If you use sass(scss) you can use the following snippet:
tr > td{
/* styles for all td*/
&:first-child{
/* styles for first */
}
&:last-child{
/* styles for last*/
}
}
It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).
It is also useful to note that you can store multiple levels of results by grouping filters
all items: {{items.length}}
filtered items: {{filteredItems.length}}
limited and filtered items: {{limitedAndFilteredItems.length}}
<div ng-repeat="item in limitedAndFilteredItems = (filteredItems = (items | filter:search) | limitTo:25)">...</div>
here's a demo fiddle
I think comboBox1.Items.Add("X");
will add string
to ComboBox, instead of ComboBoxItem
.
The right solution is
ComboBoxItem item = new ComboBoxItem();
item.Content = "A";
comboBox1.Items.Add(item);
A temporary table can have 3 kinds, the #
is the most used. This is a temp table that only exists in the current session.
An equivalent of this is @
, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session.
The ##
is one that is the same as the #
, however, the scope is wider, so you can use it within the same session, within other stored procedures.
You can create a temp table in various ways:
declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
You can use Scripting.FileSystemObject to do that thing. From the Reference:
The ReadLine method allows a script to read individual lines in a text file. To use this method, open the text file, and then set up a Do Loop that continues until the AtEndOfStream property is True. (This simply means that you have reached the end of the file.) Within the Do Loop, call the ReadLine method, store the contents of the first line in a variable, and then perform some action. When the script loops around, it will automatically drop down a line and read the second line of the file into the variable. This will continue until each line has been read (or until the script specifically exits the loop).
And a quick example:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ServerList.txt", 1)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
MsgBox strLine
Loop
objFile.Close
var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();
To print any amount of lines between printed text use:
print("Hello" + '\n' *
insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
Alternatively, you can use XPathNavigator:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();
string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");
..
/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
XPathNavigator navigator, string xpath) {
StringBuilder sb = new StringBuilder();
sb.Append(description);
XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
while (bookNodesIterator.MoveNext())
sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
return sb.ToString();
}
If anyone plan to use this implementation, You might wanna check this out and this
This is my version of that convertion code:
public class ResultSetConverter {
public static JSONArray convert(ResultSet rs) throws SQLException,
JSONException {
JSONArray json = new JSONArray();
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
while (rs.next()) {
JSONObject obj = new JSONObject();
for (int i = 1; i < numColumns + 1; i++) {
String column_name = rsmd.getColumnName(i);
if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
obj.put(column_name, rs.getArray(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
obj.put(column_name, rs.getLong(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
obj.put(column_name, rs.getFloat(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
obj.put(column_name, rs.getBoolean(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
obj.put(column_name, rs.getBlob(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
obj.put(column_name, rs.getDouble(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
obj.put(column_name, rs.getDouble(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
obj.put(column_name, rs.getInt(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
obj.put(column_name, rs.getNString(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
obj.put(column_name, rs.getString(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
obj.put(column_name, rs.getString(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
obj.put(column_name, rs.getNString(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
obj.put(column_name, rs.getNString(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
obj.put(column_name, rs.getString(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
obj.put(column_name, rs.getByte(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
obj.put(column_name, rs.getShort(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
obj.put(column_name, rs.getDate(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
obj.put(column_name, rs.getTime(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
obj.put(column_name, rs.getTimestamp(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
obj.put(column_name, rs.getBytes(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
obj.put(column_name, rs.getBytes(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
obj.put(column_name, rs.getBinaryStream(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
obj.put(column_name, rs.getBoolean(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
obj.put(column_name, rs.getClob(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
obj.put(column_name, rs.getBigDecimal(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
obj.put(column_name, rs.getBigDecimal(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
obj.put(column_name, rs.getURL(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
obj.put(column_name, rs.getRef(column_name));
} else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
} else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) {
obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
} else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) {
obj.put(column_name, rs.getObject(column_name));
} else {
obj.put(column_name, rs.getString(i));
}
}
json.put(obj);
}
return json;
}
}
Try:
javac -cp .;"C:\Users\User Name\Tomcat\apache-tomcat-7.0.108\lib\servlet-api.jar" HelloServlet.java
using windows if there are spaces in your class path.
Using c-promise2 lib the cancellable fetch with timeout might look like this one (Live jsfiddle demo):
import CPromise from "c-promise2"; // npm package
function fetchWithTimeout(url, {timeout, ...fetchOptions}= {}) {
return new CPromise((resolve, reject, {signal}) => {
fetch(url, {...fetchOptions, signal}).then(resolve, reject)
}, timeout)
}
const chain = fetchWithTimeout("https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=10s", {timeout: 5000})
.then(request=> console.log('done'));
// chain.cancel(); - to abort the request before the timeout
This code as a npm package cp-fetch
If someone is facing issue using texttocolumns function in UFT. Please try using below function.
myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true
Here we are using coma(,) as delimiter.
1) use for tommorow's date startDate: '+1d'
2) use for yesterday's date startDate: '-1d'
3) use for today's date startDate: new Date()
You should set the format of the ie font to 'embedded-opentype' and not 'eot'. For example:
src: url('fontname.eot?#iefix') format('embedded-opentype')
To elaborate on GoZoner's answer:
Your real issue here is that you are recursively calling your getter.
var x:Int
{
set
{
x = newValue * 2 // This isn't a problem
}
get {
return x / 2 // Here is your real issue, you are recursively calling
// your x property's getter
}
}
Like the code comment suggests above, you are infinitely calling the x property's getter, which will continue to execute until you get a EXC_BAD_ACCESS code (you can see the spinner in the bottom right corner of your Xcode's playground environment).
Consider the example from the Swift documentation:
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
Notice how the center computed property never modifies or returns itself in the variable's declaration.
This applies to "IntelliJ IDEA-2019.2.4" on Mac.
You can remove the blue outline by using outline: none
.
However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.
Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com
Open I
as an array:
>>> I = numpy.asarray(PIL.Image.open('test.jpg'))
Do some stuff to I
, then, convert it back to an image:
>>> im = PIL.Image.fromarray(numpy.uint8(I))
Filter numpy images with FFT, Python
If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on this page in correlation.zip.
I had issue alike (click on button, but after cancel clicked it still removes my object), so made this in such way, hope it helps someone in the future:
$('.deleteObject').click(function () {
var url = this.href;
var confirmText = "Are you sure you want to delete this object?";
if(confirm(confirmText)) {
$.ajax({
type:"POST",
url:url,
success:function () {
// Here goes something...
},
});
}
return false;
});
I think this will solve your problem. I created one directive which filters input from the user and restricts number or text which you want.
This solution is for up to Ionic-3 and Angular-4 users.
import { Directive, HostListener, Input } from '@angular/core';
import { Platform } from 'ionic-angular';
/**
* Generated class for the AlphabateInputDirective directive.
*
* See https://angular.io/api/core/Directive for more info on Angular
* Directives.
*/
@Directive({
selector: '[keyboard-input-handler]' // Attribute selector
})
export class IonicKeyboardInputHandler {
@Input("type") inputType: string;
isNumeric: boolean = true;
str: string = "";
arr: any = [];
constructor(
public platForm: Platform
) {
console.log('Hello IonicKeyboardInputHandler Directive');
}
@HostListener('keyup', ['$event']) onInputStart(e) {
this.str = e.target.value + '';
this.arr = this.str.split('');
this.isNumeric = this.inputType == "number" ? true : false;
if(e.target.value.split('.').length === 2){
return false;
}
if(this.isNumeric){
e.target.value = parseInt(this.arr.filter( c => isFinite(c)).join(''));
}
else
e.target.value = this.arr.filter( c => !isFinite(c)).join('');
return true;
}
}
In addition to the answer by fenix2222 (which worked for me) I had to modify the last line to:
config.Save(ConfigurationSaveMode.Modified);
Without this, the new value was still being written to the config file but the old value was retrieved when debugging.
Good news! awk
field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|..."
:
awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file
Returns:
tc0001 tomcat7.1 demo.example.com
tc0001 tomcat7.2 quest.example.com
tc0001 tomcat7.5 www.example.com
Here:
-F"/|="
sets the input field separator to either /
or =
. Then, it sets the output field separator to a tab.
-vOFS='\t'
is using the -v
flag for setting a variable. OFS
is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F
.
{print $3, $5, $NF}
prints the 3rd, 5th and last fields based on the input field separator.
See another example:
$ cat file
hello#how_are_you
i#am_very#well_thank#you
This file has two fields separators, #
and _
. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!
$ awk -F"#|_" '{print $2}' file
how
am
Where the files are numbered as follows:
hello#how_are_you i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^ ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
1 2 3 4 1 2 3 4 5 6
Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
Directive:
myApp.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '=tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass('tooltip-title');
}
},
}
});
With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.
try http://code.google.com/p/swinghtmltemplate/
this will allow you to create gui with html-like syntax
To set timeout on a per page level, you could use this simple code:
Page.Server.ScriptTimeout = 60;
Note: 60 means 60 seconds, this time-out applies only if the debug attribute in the compilation element is False.
Note: This answer is less current than it was when posted in 2009. Using the subprocess
module shown in other answers is now recommended in the docs
(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)
If you want your process to start in the background you can either use system()
and call it in the same way your shell script did, or you can spawn
it:
import os
os.spawnl(os.P_DETACH, 'some_long_running_command')
(or, alternatively, you may try the less portable os.P_NOWAIT
flag).
See the documentation here.
use --cacert
to specify a .crt
file.
ca-root-nss.crt
for example.
First of all, I try to install the glyphicons fonts by the "oficial" way, with the zip file. I could not do it.
This is my step-by-step solution:
However, for a more easy acces, this is the link of the woff file.
http://getbootstrap.com/dist/fonts/glyphicons-halflings-regular.woff
If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, §8.4.2. Method Signature:
Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.
If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.
If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.
public ActionResult Index() {
return new RedirectResult("http://www.website.com");
}
Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Set This in OkHttpClient.Builder() Object
val httpClient = OkHttpClient.Builder()
httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES) // read timeout
By default, the JDBCTemplate
does its own PreparedStatement
internally, if you just use the .update(String sql, Object ... args)
form. Spring, and your database, will manage the compiled query for you, so you don't have to worry about opening, closing, resource protection, etc. One of the saving graces of Spring. A link to Spring 2.5's documentation on this. Hope it makes things clearer. Also, statement caching can be done at the JDBC level, as in the case of at least some of Oracle's JDBC drivers.
That will go into a lot more detail than I can competently.
I came here because I needed to create a {{ render() }}
function in Twig, to simulate Symfony2's behaviour. Rendering controllers from view is really cool to display independant widgets or ajax-reloadable stuffs.
Even if you're not a Twig user, you can still take this helper and use it as you want in your views to render a controller, using <?php echo twig_render('welcome/index', $param1, $param2, $_); ?>
. This will echo everything your controller outputted.
Here it is:
helpers/twig_helper.php
<?php
if (!function_exists('twig_render'))
{
function twig_render()
{
$args = func_get_args();
$route = array_shift($args);
$controller = APPPATH . 'controllers/' . substr($route, 0, strrpos($route, '/'));
$explode = explode('/', $route);
if (count($explode) < 2)
{
show_error("twig_render: A twig route is made from format: path/to/controller/action.");
}
if (!is_file($controller . '.php'))
{
show_error("twig_render: Controller not found: {$controller}");
}
if (!is_readable($controller . '.php'))
{
show_error("twig_render: Controller not readable: {$controller}");
}
require_once($controller . '.php');
$class = ucfirst(reset(array_slice($explode, count($explode) - 2, 1)));
if (!class_exists($class))
{
show_error("twig_render: Controller file exists, but class not found inside: {$class}");
}
$object = new $class();
if (!($object instanceof CI_Controller))
{
show_error("twig_render: Class {$class} is not an instance of CI_Controller");
}
$method = $explode[count($explode) - 1];
if (!method_exists($object, $method))
{
show_error("twig_render: Controller method not found: {$method}");
}
if (!is_callable(array($object, $method)))
{
show_error("twig_render: Controller method not visible: {$method}");
}
call_user_func_array(array($object, $method), $args);
$ci = &get_instance();
return $ci->output->get_output();
}
}
Specific for Twig users (adapt this code to your Twig implementation):
libraries/Twig.php
$this->_twig_env->addFunction('render', new Twig_Function_Function('twig_render'));
Usage
{{ render('welcome/index', param1, param2, ...) }}
If you need to change the figure size after you have created it, use the methods
fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)
where value_height
and value_width
are in inches. For me this is the most practical way.
Use max-width
on the images too. Change:
.erb-image-wrapper img{
width:100% !important;
height:100% !important;
display:block;
}
to...
.erb-image-wrapper img{
max-width:100% !important;
max-height:100% !important;
display:block;
}
This is not an answer to your question but I believe it is the solution to your problem. The interface org.springframework.data.repository.CrudRepository
does indeed have methods that return java.lang.Iterable
but you should not use this interface. Instead use sub interfaces, in your case org.springframework.data.mongodb.repository.MongoRepository
. This interface has methods that return objects of type java.util.List
.
I use <br>
in a CDATA
tag.
As an example, my strings.xml file contains an item like this:
<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>
and prints
My name is John
Nice to meet you
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
Construct and fill out a hidden method=POST action="http://example.com/vote"
form and submit it, rather than using window.location
at all.
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
1)
var merged = {};
for(key in obj1)
merged[key] = obj1[key];
for(key in obj2)
merged[key] = obj2[key];
2)
var merged = {};
Object.keys(obj1).forEach(k => merged[k] = obj1[k]);
Object.keys(obj2).forEach(k => merged[k] = obj2[k]);
Object.keys(obj1)
.concat(Object.keys(obj2))
.forEach(k => merged[k] = k in obj2 ? obj2[k] : obj1[k]);
3) Simplest way:
var merged = {};
Object.assign(merged, obj1, obj2);
Also lazy
is useful without cyclic dependencies, as in the following code:
abstract class X {
val x: String
println ("x is "+x.length)
}
object Y extends X { val x = "Hello" }
Y
Accessing Y
will now throw null pointer exception, because x
is not yet initialized.
The following, however, works fine:
abstract class X {
val x: String
println ("x is "+x.length)
}
object Y extends X { lazy val x = "Hello" }
Y
EDIT: the following will also work:
object Y extends { val x = "Hello" } with X
This is called an "early initializer". See this SO question for more details.
Transient, scoped and singleton define object creation process in ASP.NET MVC core DI when multiple objects of the same type have to be injected. In case you are new to dependency injection you can see this DI IoC video.
You can see the below controller code in which I have requested two instances of "IDal" in the constructor. Transient, Scoped and Singleton define if the same instance will be injected in "_dal" and "_dal1" or different.
public class CustomerController : Controller
{
IDal dal = null;
public CustomerController(IDal _dal,
IDal _dal1)
{
dal = _dal;
// DI of MVC core
// inversion of control
}
}
Transient: In transient, new object instances will be injected in a single request and response. Below is a snapshot image where I displayed GUID values.
Scoped: In scoped, the same object instance will be injected in a single request and response.
Singleton: In singleton, the same object will be injected across all requests and responses. In this case one global instance of the object will be created.
Below is a simple diagram which explains the above fundamental visually.
The above image was drawn by the SBSS team when I was taking ASP.NET MVC training in Mumbai. A big thanks goes to the SBSS team for creating the above image.
You can try to rename the python executable in the python3 folder to python3, that is if it was named python formally... it worked for me
As stated already, running your code through the W3C Validator is great but if your page is complex, you still may not know exactly where to find the open div.
I like using tabs to indent my code. It keeps it visually organized so that these issues are easier to find, children, siblings, parents, etc... they'll appear more obvious.
EDIT: Also, I'll use a few HTML comments to mark closing tags in the complex areas. I keep these to a minimum for neatness.
<body>
<div>
Main Content
<div>
Div #1 content
<div>
Child of div #1
<div>
Child of child of div #1
</div><!--// close of child of child of div #1 //-->
</div><!--// close of child of div #1 //-->
</div><!--// close of div #1 //-->
<div>
Div #2 content
</div>
<div>
Div #3 content
</div>
</div><!--// close of Main Content div //-->
</body>
If you need to print the number you can use printf
System.out.printf("%02d", num);
You can use
String.format("%02d", num);
or
(num < 10 ? "0" : "") + num;
or
(""+(100+num)).substring(1);
By POST file uploads are done (commonly, there are also other methods). Look into the method attribute of the form which contains the file-upload field ;)
The lowest limit of any related setting supersedes a higher setting:
See Handling file uploads: Common Pitfals which explains this in detail and how to calculate the values.
Go to the Config button (up right) and select the Autostart for Apache.
You can use a2enmod
or a2dismod
to enable/disable modules by name.
From terminal, run: sudo a2enmod php5
to enable PHP5 (or some other module), then sudo service apache2 reload
to reload the Apache2 configuration.
check your application.properties
changing
spring.datasource.driverClassName=com.mysql.jdbc.Driver
to
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
worked for me. Full config:
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
You can remove elements from ArrayList
using ListIterator
,
ListIterator listIterator = List_Of_Array.listIterator();
/* Use void remove() method of ListIterator to remove an element from List.
It removes the last element returned by next or previous methods.
*/
listIterator.next();
//remove element returned by last next method
listIterator.remove();//remove element at 1st position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 3rd position
listIterator.next();
listIterator.next();
listIterator.remove();//remove element at 5th position
This will do. Pretty trustworthy. : )
""+number;
Just to clarify, this works and acceptable to use unless you are looking for micro optimization.
They can't be initialised inside the class, but they can be initialised outside the class, in a source file:
// inside the class
class Thing {
static string RE_ANY;
static string RE_ANY_RELUCTANT;
};
// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";
Update
I've just noticed the first line of your question - you don't want to make those functions static
, you want to make them const
. Making them static
means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const
simply means that they can't modify any members, but can still access them.
For new comers,
matplotlib.pyplot.switch_backend(newbackend)
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
Another reason, Check your Developer account is connected with xCode
Html Markup
Tool-tip Control with class ".why", and Tool-tip Content Area with class ".customTolltip"
$(function () {
$('.why').attr('title', function () {
return $(this).next('.customTolltip').remove().html();
});
$(document).tooltip();
});
Both are supported. To quote the Arduino homepage,
The core libraries are written in C and C++ and compiled using avr-gcc
Note that C++ is a superset of C (well, almost), and thus can often look very similar. I am not an expert, but I guess that most of what you will program for the Arduino in your first year on that platform will not need anything but plain C.
change the focused border to none
TextField(
decoration: new InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
hintText: 'Subject'
),
),
With C++11 and two simple templates, you can write
for ( auto x: range(v1+4,v1+6) ) {
x*=2;
cout<< x <<' ';
}
as a replacement for for_each
or a loop. Why choose it boils down to brevity and safety, there's no chance of error in an expression that's not there.
For me, for_each
was always better on the same grounds when the loop body is already a functor, and I'll take any advantage I can get.
You still use the three-expression for
, but now when you see one you know there's something to understand there, it's not boilerplate. I hate boilerplate. I resent its existence. It's not real code, there's nothing to learn by reading it, it's just one more thing that needs checking. The mental effort can be measured by how easy it is to get rusty at checking it.
The templates are
template<typename iter>
struct range_ {
iter begin() {return __beg;} iter end(){return __end;}
range_(iter const&beg,iter const&end) : __beg(beg),__end(end) {}
iter __beg, __end;
};
template<typename iter>
range_<iter> range(iter const &begin, iter const &end)
{ return range_<iter>(begin,end); }
You can just modify any xml files in /res folder and even just add a space and save, it will be regenerated.
Well, on Windows I happily run diff
and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.
So, my answer is that the Windows equivalent of diff
, is none other than diff
itself!
With lodash:
_.each([1, 2, 3], (item) => {
doSomeThing(item);
});
//Or:
_.each([1, 2, 3], doSomeThing);
Or if you want to do something N times:
const N = 10;
_.times(N, () => {
doSomeThing();
});
//Or shorter:
_.times(N, doSomeThing);
Refer to this link for lodash
installation
Just use this function:
function sum(pArray)
{
pArray = pArray.reduce(function (a, b) {
return a + b;
}, 0);
return pArray;
}
function sum(pArray)_x000D_
{_x000D_
pArray = pArray.reduce(function (a, b) {_x000D_
return a + b;_x000D_
}, 0);_x000D_
_x000D_
return pArray;_x000D_
}_x000D_
_x000D_
var arr = [1, 4, 5];_x000D_
_x000D_
console.log(sum(arr));
_x000D_
I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.
D:\>InterlockVsMonitor.exe 16
Using 16 threads:
InterlockAtomic.RunIncrement (ns): 8355 Average, 8302 Minimal, 8409 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 7077 Average, 6843 Minimal, 7243 Maxmial
D:\>InterlockVsMonitor.exe 4
Using 4 threads:
InterlockAtomic.RunIncrement (ns): 4319 Average, 4319 Minimal, 4321 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 933 Average, 802 Minimal, 1018 Maxmial
Operation timed out (IPv6 issues)# You may run into errors if IPv6 is not configured correctly. A common error is:
The "https://getcomposer.org/version" file could not be downloaded: failed to
open stream: Operation timed out
We recommend you fix your IPv6 setup. If that is not possible, you can try the following workarounds:
Workaround Linux:
On linux, it seems that running this command helps to make ipv4 traffic have a higher prio than ipv6, which is a better alternative than disabling ipv6 entirely:
sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf"
Workaround Windows:
On windows the only way is to disable ipv6 entirely I am afraid (either in windows or in your home router).
Workaround Mac OS X:
Get name of your network device:
networksetup -listallnetworkservices
Disable IPv6 on that device (in this case "Wi-Fi"):
networksetup -setv6off Wi-Fi
Run composer ...
You can enable IPv6 again with:
networksetup -setv6automatic Wi-Fi
That said, if this fixes your problem, please talk to your ISP about it to try and resolve the routing errors. That's the best way to get things resolved for everyone.
Hoping it will help you!
With create-react-app
there is public folder (with index.html...).
If you place your "myImage.png" there, say under img sub-folder, then you can access them through:
<img src={window.location.origin + '/img/myImage.png'} />
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
It means that es3.c
does not define a main
function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.
To compile only to an object file, use the -c
option:
gcc es3.c -c
gcc es3.o main.c -o es3
The above compiles es3.c
to an object file, then compiles a file main.c
that would contain the main
function, and the linker merges es3.o
and main.o
into an executable called es3
.
i would prefer to use onclick=""
attribute as it is easy to use and understand for newbie like
<tr onclick="window.location='any-page.php'">
<td>UserName</td>
<td>Email</td>
<td>Address</td>
</tr>
This will work in Python 3
import urllib.request
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need
Use the glide library. It worked for me and will work for your code too.It works for both images as well as gifs too.
ImageView imageView = (ImageView) findViewById(R.id.test_image);
GlideDrawableImageViewTarget imagePreview = new GlideDrawableImageViewTarget(imageView);
Glide
.with(this)
.load(url)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
return false;
}
})
.into(imagePreview);
}
1. click the right bottom arrow in the toolbar
2. Downloading Bar
3. Needs to restart