Try following solution and let me know in case of any issues:
driver.get('https://example.com/')
driver.switchTo().alert().sendKeys("username" + Keys.TAB + "password");
driver.switchTo().alert().accept();
This is working fine for me
Here is how I do it in Python with Selenium 2.48.0:
from selenium.webdriver import Firefox
driver = Firefox()
driver.set_window_position(0, 0)
driver.set_window_size(1024, 768)
For me it was just a matter of changing the path variable to: 'C:\Program Files\Mozilla Firefox' instead of 'C:\Program Files (x86)\Mozilla Firefox'
For people out there asking how to setup proxy server in chrome which needs authentication should follow these steps.
Try this:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
For me, the answer is Crystal Syntax, the BASIC-like language used by Crystal Reports. Trying to accomplish anything other than mere comparisons is difficult at best and impossible at worst. Granted, they do arrays fairly well:
{some_database_field} IN ["firstValue", "secondValue", "thirdValue"]
But the following doesn't work at all:
{some_database_field} NOT IN ["firstValue", "secondValue", "thirdValue"]
Even though the language does have a NOT operator.
A socket is a data I/O mechanism. A port is a contractual concept of a communication protocol. A socket can exist without a port. A port can exist witout a specific socket (e.g. if several sockets are active on the same port, which may be allowed for some protocols).
A port is used to determine which socket the receiver should route the packet to, with many protocols, but it is not always required and the receiving socket selection can be done by other means - a port is entirely a tool used by the protocol handler in the network subsystem. e.g. if a protocol does not use a port, packets can go to all listening sockets or any socket.
Egypt (free software)
KcacheGrind (GPL)
Graphviz (CPL)
CodeViz (GPL)
HTML
<div class="outside">
<div class="inside">
<p>Centered Text</p>
</div>
</div>
CSS
.outside {
position: absolute;
display: table;
}
.inside {
display: table-cell;
vertical-align: middle;
text-align: center;
}
You're pretty much right about cout
and cin
. They are objects (not functions) defined inside the std
namespace. Here are their declarations as defined by the C++ standard:
Header
<iostream>
synopsis#include <ios> #include <streambuf> #include <istream> #include <ostream> namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; extern wistream wcin; extern wostream wcout; extern wostream wcerr; extern wostream wclog; }
::
is known as the scope resolution operator. The names cout
and cin
are defined within std
, so we have to qualify their names with std::
.
Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:
class foo
{
public:
foo();
void bar();
};
The constructor named foo
is a member of the class named foo
. They have the same name because its the constructor. The function bar
is also a member of foo
.
Because they are members of foo
, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar
outside the class, you need to do it like so:
foo::foo()
{
// Implement the constructor
}
void foo::bar()
{
// Implement bar
}
This is because they are being defined outside the class. If you had not put the foo::
qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo
. For example, this is entirely different bar
:
void bar()
{
// Implement different bar
}
It's allowed to have the same name as the function in the foo
class because it's in a different scope. This bar
is in the global scope, whereas the other bar
belonged to the foo
class.
jQuery is just JavaScript, don't think very differently about it! Like you would do in 'normal' JS, you add an event listener to the buttons and change the action attribute of the form. In jQuery this looks something like:
$('#button1').click(function(){
$('#your_form').attr('action', 'http://uri-for-button1.com');
});
This code is the same for the second button, you only need to change the id of your button and the URI where the form should be submitted to.
This work for me.
function Minify_Html($Html)
{
$Search = array(
'/(\n|^)(\x20+|\t)/',
'/(\n|^)\/\/(.*?)(\n|$)/',
'/\n/',
'/\<\!--.*?-->/',
'/(\x20+|\t)/', # Delete multispace (Without \n)
'/\>\s+\</', # strip whitespaces between tags
'/(\"|\')\s+\>/', # strip whitespaces between quotation ("') and end tags
'/=\s+(\"|\')/'); # strip whitespaces between = "'
$Replace = array(
"\n",
"\n",
" ",
"",
" ",
"><",
"$1>",
"=$1");
$Html = preg_replace($Search,$Replace,$Html);
return $Html;
}
You use css to change the opacity. To cope with IE you'd need something like:
.opaque {
opacity : 0.3;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
filter: alpha(opacity=30);
}
But the only problem with this is that it means anything inside the container will also be 0.3 opacity. Thus you'll have to change your HTML to have another container, not inside the transparent one, that holds your content.
Otherwise the png technique, would work. Except you'd need a fix for IE6, which in itself could cause problems.
This is very handy when using a method that would otherwise be ambiguous. For example: JDialog has constructors with the following signatures:
JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
I need to use this constructor, because I want to set the GraphicsConfiguration, but I have no parent for this dialog, so the first argument should be null. Using
JDialog(null, String, boolean, Graphicsconfiguration)
is ambiguous, so in this case I can narrow the call by casting null to one of the supported types:
JDialog((Frame) null, String, boolean, GraphicsConfiguration)
To retrieve text of an auto generated span value just do this :
var al = $("#id-span-name").text();
alert(al);
You can also combine them I guess:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
</body>
</html>
You could also use
print(tbl_df(df), n=40)
or with the help of the pipe operator
df %>% tbl_df %>% print(n=40)
To print all rows specify tbl_df %>% print(n = Inf)
A generic solution that will work with any testing framework (if your class is non-final
) is to manually create your own mock.
This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.
To mock a private method directly, you'll need to use PowerMock as shown in the other answer.
# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName
Here is the Jquery Code
$(document).ready(function () {
var el = $('#Container');
var originalelpos = el.offset().top; // take it where it originally is on the page
//run on scroll
$(window).scroll(function () {
var el = $('#Container'); // important! (local)
var elpos = el.offset().top; // take current situation
var windowpos = $(window).scrollTop();
var finaldestination = windowpos + originalelpos;
el.stop().animate({ 'top': finaldestination }, 1000);
});
});
Using Java 8 try with resources:
StringBuilder stringBuilder = new StringBuilder();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
char[] charBuffer = new char[1024];
int bytesRead;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
}
Looking at the Volley perspective here are some advantages for your requirement:
Volley, on one hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks
Pros and cons of Volley:
So what’s nice about Volley?
The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.
NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.
Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.
Volley apparently has futures, too. Check out RequestFuture if you’re interested.
If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.
Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance )
Volley plays nice with the Activity life cycle.
Problems With Volley:
Since Volley is new, few things are not supported yet, but it's fixed.
Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)
status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley)
Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick!
it's less documented but many of the people are supporting volley in github, java like documentation can be found here. On android developer website, you may find guide for Transmitting Network Data Using Volley. And volley source code can be found at Google Git
To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above)
Also you can read this Comparing Volley's image loading with Picasso
Retrofit:
It's released by Square, This offers very easy to use REST API's (Update: Voila! with NIO support)
Pros of Retrofit:
Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.
We can use it with any serialization library, with error handling.
Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2
Cons of Retrofit for version 1.6:
Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support.
Minimum threading assistance can result call back hell if we use this in an improper way.
(All above Cons have been solved in the new version of Retrofit 2.0 beta)
========================================================================
Update:
Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):
(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)
In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. That is a massive real-world difference. In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically.
RetroFit Wins in benchmark test!
In the end, we decided to go with Retrofit for our application. Not only is it ridiculously fast, but it meshes quite well with our existing architecture. We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. Now that we have a few fragments completely converted, it’s pretty painless. There were some growing pains and issues that we had to overcome, but overall it went smoothly. In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it.
When to use Volley?!
We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! also Volley has better memory related error handling than Retrofit!
OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.
Source, credit: volley-vs-retrofit by Mr. Josh Ruesch
Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.
Here's a one line solution to remove columns based on duplicate column names:
df = df.loc[:,~df.columns.duplicated()]
How it works:
Suppose the columns of the data frame are ['alpha','beta','alpha']
df.columns.duplicated()
returns a boolean array: a True
or False
for each column. If it is False
then the column name is unique up to that point, if it is True
then the column name is duplicated earlier. For example, using the given example, the returned value would be [False,False,True]
.
Pandas
allows one to index using boolean values whereby it selects only the True
values. Since we want to keep the unduplicated columns, we need the above boolean array to be flipped (ie [True, True, False] = ~[False,False,True]
)
Finally, df.loc[:,[True,True,False]]
selects only the non-duplicated columns using the aforementioned indexing capability.
Note: the above only checks columns names, not column values.
EDIT:
So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?
This question could be:
A request for advice; or
A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.
People differ in their predilection for following:
Official advice; or
The preponderance of practice.
Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!
In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.
By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.
Whatever your personal inclination, be it to follow one path or the other, I do not object.
(End of edit.)
The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).
As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.
As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.
Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."
Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."
As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.
The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.
Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!
Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?
Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).
Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.
Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.
Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.
Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".
The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.
".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.
Swift 4 with customType:
let button = UIButton(frame: aRectHere)
let buttonImage = UIImage(named: "imageName")
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
Just remember:
So, choose the way what you want to handle your branch.
You'd better know the difference between merge and rebase :)
To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length
.
double sum = 0.0;
int length = 0;
for( double number : numbers ) {
sum += number;
length++;
}
return sum/length;
Variance is calculated similarly. Standard deviation is simply the square root of the variance:
double stddev = Math.sqrt( variance );
Try to replace your initialization code with:
ProcessStartInfo info
= new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");
Using non full filepath on Process.Start
only works if the file is found in System32 folder.
You can use if-else statements with || operators (or-operator) like:
if(case1 == true || case2 == true || case3 == true)
{
Do this!...
}
else if(case4 == true || case5 == true || case6 == true)
{
Do this!...
}
else if(case7 == true || case8 == true || case9 == true)
{
Do this!...
}
If you install the Tortoise SVN, Please go to task manager and stop it. Then try to delete the folder. it will work
As Java8 add new Date functions, we can do this easily.
// If you have instant, then:
Instant instant1 = Instant.now();
Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
System.out.println(day1); //2019-01-14T00:00:00Z
// If you have Date, then:
Date date = new Date();
Instant instant2 = date.toInstant();
Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
System.out.println(day2); //2019-01-14T00:00:00Z
// If you have LocalDateTime, then:
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(day3); //2019-01-14T00:00
String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(format);//2019-01-14T00:00:00
Apparently the change event is not fired if a selection already exists when using data. I ended up updating the data manually on select to resolve the problem.
$("#search_code").on("select2-selecting", function(e) {
$("#search_code").select2("data",e.choice);
});
I know this is pretty late but hopefully this answer will save others time.
$UUID_RE = join '-', map { "[0-9a-f]{$_}" } 8, 4, 4, 4, 12;
BTW, allowing only 4 on one of the positions is only valid for UUIDv4. But v4 is not the only UUID version that exists. I have met v1 in my practice as well.
in case you use SUSE
sudo yast2 -i ruby-devel
I did a quick performance check on these with perfplot (a project of mine) and found that it's hard to recommend anything else but numpy (note the log scale):
Code to reproduce the plot:
import perfplot
import numpy
def sorted_enumerate(seq):
return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
def sorted_enumerate_key(seq):
return [x for x, y in sorted(enumerate(seq), key=lambda x: x[1])]
def sorted_range(seq):
return sorted(range(len(seq)), key=seq.__getitem__)
def numpy_argsort(x):
return numpy.argsort(x)
perfplot.save(
"argsort.png",
setup=lambda n: numpy.random.rand(n),
kernels=[sorted_enumerate, sorted_enumerate_key, sorted_range, numpy_argsort],
n_range=[2 ** k for k in range(15)],
xlabel="len(x)",
)
let attrString = NSAttributedString (
string: "title-title-title",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
I'm sure Apple have annoyed many people with this change. I develop a bookkeeping app for iOS and have an online service to sync changes made on different devices. The service maintains a database of all devices and the changes that need to be propagated to them. Therefore it's important to know which devices are which. I'm keeping track of devices using the UIDevice uniqueIdentifier and for what it's worth, here are my thoughts.
Generate a UUID and store in user defaults? No good because this does not persist when the user deletes the app. If they install again later the online service should not create a new device record, that would waste resources on the server and give a list of devices containing the same one two or more times. Users would see more than one "Bob's iPhone" listed if they re-installed the app.
Generate a UUID and store in the keychain? This was my plan, since it persists even when the app is uninstalled. But when restoring an iTunes backup to a new iOS device, the keychain is transferred if the backup is encrypted. This could lead to two devices containing the same device id if the old and new devices are both in service. These should be listed as two devices in the online service, even if the device name is the same.
Generate a hash the MAC address and bundle id? This looks like the best solution for what I need. By hashing with the bundle id, the generated device id is not going to enable the device to be tracked across apps and I get a unique ID for the app+device combination.
It's interesting to note that Apple's own documentation refers to validating Mac App Store receipts by computing a hash of the system MAC address plus the bundle id and version. So this seems allowable by policy, whether it passes through app review I don't yet know.
Initially create asset folder and copy the fontawesome icon (.ttf) How to create asset folder?
app-->right Click -->new-->folder --> asset folder
next step download how to download .ttf file? click here--> and click download button after download extract and open web fonts. finally choose true text style(ttf)paste asset folder.
how to design xml and java file in android ?
app-->res-->values string.xml
resources
string name="calander_font" > <string
resources
this example of one font more Unicode click here
Activity_main.xml
<TextView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="@+id/calander_view"/>
MainActivity.java
calander_tv = (TextView)findViewById(R.id.calander_view);
Typeface typeface = Typeface.createFromAsset(getAssets(),"/fonts/fa-solid-900.ttf");
calander_tv.setTypeface(typeface);
calander_tv.setText(R.string.calander_font);
Output:
Use dt.days
to obtain the days attribute as integers.
For eg:
In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))
In [15]: s
Out[15]:
0 1 days 00:00:00
1 3 days 02:00:00
2 5 days 04:00:00
3 7 days 06:00:00
4 9 days 08:00:00
5 11 days 10:00:00
dtype: timedelta64[ns]
In [16]: s.dt.days
Out[16]:
0 1
1 3
2 5
3 7
4 9
5 11
dtype: int64
More generally - You can use the .components
property to access a reduced form of timedelta
.
In [17]: s.dt.components
Out[17]:
days hours minutes seconds milliseconds microseconds nanoseconds
0 1 0 0 0 0 0 0
1 3 2 0 0 0 0 0
2 5 4 0 0 0 0 0
3 7 6 0 0 0 0 0
4 9 8 0 0 0 0 0
5 11 10 0 0 0 0 0
Now, to get the hours
attribute:
In [23]: s.dt.components.hours
Out[23]:
0 0
1 2
2 4
3 6
4 8
5 10
Name: hours, dtype: int64
this is what worked for me for <span class="navigation-pipe">></span>
display:inline-block;
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=4);
just need display:inline-block or block to rotate. So basically first answer is good. But -180 didn't worked.
Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.
Difference between these to methods are, how you want to pass the parameters.
“A for array and C for comma” is a handy mnemonic.
I also tried http://www.eclipse.org/cdt/ in Ubuntu 12.04.2 LTS and works fine!
I save the file somewhere, let´s say into my home directory. Open a console or terminal, and type:
>>cd ~; tar xvzf eclipse*.tar.gz;
Remember for having Eclipse running in Linux, it is required a JVM, so download a jdk file e.g jdk-7u17-linux-i586.rpm (I cann´t post the link due to my low reputation) ... anyway
Install the .rpm file following http://www.wikihow.com/Install-Java-on-Linux
Find the path to the Java installation, by typing:
>>which java
I got /usr/bin/java. To start up Eclipse, type:
>>cd ~/eclipse; ./eclipse -vm /usr/bin/java
Also, once everything is installed, in the home directory, you can double-click the executable icon called eclipse, and then you´ll have it!. In case you like an icon, create a .desktop file in /usr/share/applications:
>>sudo gedit /usr/share/applications/eclipse.desktop
The .desktop file content is as follows:
[Desktop Entry]
Name=Eclipse
Type=Application
Exec="This is the path of the eclipse executable on your machine"
Terminal=false
Icon="This is the path of the icon.xpm file on your machine"
Comment=Integrated Development Environment
NoDisplay=false
Categories=Development;IDE
Name[en]=eclipse.desktop
Best luck!
If the top commit is pointed to by HEAD then you can do something like this:
commit1 -> HEAD
commit2 -> HEAD~1
commit3 -> HEAD~2
Diff between the first and second commit:
git diff HEAD~1 HEAD
Diff between first and third commit:
git diff HEAD~2 HEAD
Diff between second and third commit:
git diff HEAD~2 HEAD~1
And so on...
Try this
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '03:30:00')
I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.
I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log
MySQL could not start.
I resolved it by removing the following directory: /var/lib/mysql/mysql
sudo rm -rf /var/lib/mysql/mysql
This leaves your other DB related files in place, only removing the mysql related files.
After running these:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
Then reinstalling mysql:
sudo apt-get install mysql-server
It worked perfectly.
SELECT DATENAME(DW,CONVERT(VARCHAR(20),GETDATE(),101))
The [:-1]
removes the last element. Instead of
a[3:-1]
write
a[3:]
You can read up on Python slicing notation here: Explain Python's slice notation
NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.
I like
Get-WmiObject Win32_computersystem | format-custom *
That seems to expand everything.
There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).
Although most often I use
Get-WmiObject Win32_computersystem | fl *
It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.
JDK is the Java Development Kit (used to develop Java software).
JRE is the Java Runtime Environment (used to run any .jar file 'Java software').
The JDK contains a JRE inside it.
On Windows when you update Java, it updates the JRE automatically.
On Mac you do not have a JRE separated you have it, but inside the JDK, so when you update Java it will update your JRE which is inside your JDK; it doesn't install an JDK for you. You need to get it from somewhere else.
Converting a number from positive to negative, or negative to positive:
public static decimal Reverse(this decimal source)
{
return source * decimal.MinusOne;
}
As I understand your question..
From Java List class you have to methods add(E e)
and get(int position)
.
add(E e)
Appends the specified element to the end of this list (optional operation).
get(int index)
Returns the element at the specified position in this list.
Example:
List<String> myString = new ArrayList<String>();
// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");
// retrieving data from string list array in for loop
for (int i=0;i < myString.size();i++)
{
Log.i("Value of element "+i,myString.get(i));
}
But efficient way to iterate thru loop
for (String value : myString)
{
Log.i("Value of element ",value);
}
nchar(YOURSTRING)
you may need to convert to a character vector first;
nchar(as.character(YOURSTRING))
You should use Array.prototype.reduce to do this. I did do a little JS perf test to verify that this is more performant than doing a .filter
+ .map
.
$scope.appIds = $scope.applicationsHere.reduce(function(ids, obj){
if(obj.selected === true){
ids.push(obj.id);
}
return ids;
}, []);
Just for the sake of clarity, here's the sample .reduce
I used in the JSPerf test:
var things = [_x000D_
{id: 1, selected: true},_x000D_
{id: 2, selected: true},_x000D_
{id: 3, selected: true},_x000D_
{id: 4, selected: true},_x000D_
{id: 5, selected: false},_x000D_
{id: 6, selected: true},_x000D_
{id: 7, selected: false},_x000D_
{id: 8, selected: true},_x000D_
{id: 9, selected: false},_x000D_
{id: 10, selected: true},_x000D_
];_x000D_
_x000D_
_x000D_
var ids = things.reduce((ids, thing) => {_x000D_
if (thing.selected) {_x000D_
ids.push(thing.id);_x000D_
}_x000D_
return ids;_x000D_
}, []);_x000D_
_x000D_
console.log(ids)
_x000D_
EDIT 1
Note, As of 2/2018 Reduce + Push is fastest in Chrome and Edge, but slower than Filter + Map in Firefox
The following expression worked for me:
SELECT CONVERT(VARCHAR(1000), varbinary_value, 2);
Here are more details on the choice of style (the third parameter).
In most cases, this will install the latest version of the module published on npm.
npm install express --save
or better to upgrade module to latest version use:
npm install express@latest --save --force
--save
: Package will appear in your dependencies.
More info: npm-install
If you are using PHP you can use this, and I'm sure it's almost similar in other languages as well
$WebsiteURL = "https://api.telegram.org/bot".$BotToken;
$text = "<b>This</b> <i>is some Text</i>";
$Update = file_get_contents($WebsiteURL."/sendMessage?chat_id=$chat_id&text=$text&parse_mode=html);
echo $Update;
Here is the list of all tags that you can use
<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<a href="http://www.example.com/">inline URL</a>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>
While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.
As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:
div#top-level
declarations: ...
div.inside
declarations: ...
&:first-child
declarations: ...
which compiles as one would expect:
div#top-level{
declarations... }
div#top-level div.inside {
declarations... }
div#top-level div.inside:first-child {
declarations... }
I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.
YES You can create abstract class with out any abstract method the best example of abstract class without abstract method is HttpServlet
Abstract Method is a method which have no body, If you declared at least one method into the class, the class must be declared as an abstract its mandatory BUT if you declared the abstract class its not mandatory to declared the abstract method inside the class.
You cannot create objects of abstract class, which means that it cannot be instantiated.
Old question but this is a rather simple task that can be solved properly with core JS... without the Class abstraction of ES6. In fact as far as i can tell, the Class abstraction do not even solve this problem.
We can do this job both with the good old constructor function or even better with Object.create()
. Lets go with the constructor first. This will essentially be a similar solution to georgebrock's answer which is criticised because all restaurants created by the Restaurant
constructor will have the same private methods. I will try to overcome that limitation.
function restaurantFactory(name,menu){
function Restaurant(name){
this.name = name;
}
function prototypeFactory(menu){
// This is a private function
function calculateBill(item){
return menu[item] || 0;
}
// This is the prototype to be
return { constructor: Restaurant
, askBill : function(...items){
var cost = items.reduce((total,item) => total + calculateBill(item) ,0)
return "Thank you for dining at " + this.name + ". Total is: " + cost + "\n"
}
, callWaiter : function(){
return "I have just called the waiter at " + this.name + "\n";
}
}
}
Restaurant.prototype = prototypeFactory(menu);
return new Restaurant(name,menu);
}
var menu = { water: 1
, coke : 2
, beer : 3
, beef : 15
, rice : 2
},
name = "Silver Scooop",
rest = restaurantFactory(name,menu);
console.log(rest.callWaiter());
console.log(rest.askBill("beer", "beef"));
_x000D_
Now obviously we can not access menu
from outside but we may easily rename the name
property of a restaurant.
This can also be done with Object.create()
in which case we skip the constructor function and simply do like var rest = Object.create(prototypeFactory(menu))
and add the name property to the rest
object afterwards like rest.name = name
.
Focusing on startswith, if you are sure strings are not empty, adding a test on the first char, before the comparison, the strlen, etc., speeds things up a bit:
function startswith5b($haystack, $needle) {
return ($haystack{0}==$needle{0})?strncmp($haystack, $needle, strlen($needle)) === 0:FALSE;
}
It is somehow (20%-30%) faster. Adding another char test, like $haystack{1}===$needle{1} does not seem to speedup things much, may even slow down.
===
seems faster than ==
Conditional operator (a)?b:c
seems faster than if(a) b; else c;
For those asking "why not use strpos?" calling other solutions "unnecessary work"
strpos is fast, but it is not the right tool for this job.
To understand, here is a little simulation as an example:
Search a12345678c inside bcdefga12345678xbbbbb.....bbbbba12345678c
What the computer does "inside"?
With strccmp, etc...
is a===b? NO
return false
With strpos
is a===b? NO -- iterating in haysack
is a===c? NO
is a===d? NO
....
is a===g? NO
is a===g? NO
is a===a? YES
is 1===1? YES -- iterating in needle
is 2===3? YES
is 4===4? YES
....
is 8===8? YES
is c===x? NO: oh God,
is a===1? NO -- iterating in haysack again
is a===2? NO
is a===3? NO
is a===4? NO
....
is a===x? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
is a===b? NO
...
... may many times...
...
is a===b? NO
is a===a? YES -- iterating in needle again
is 1===1? YES
is 2===3? YES
is 4===4? YES
is 8===8? YES
is c===c? YES YES YES I have found the same string! yay!
was it at position 0? NOPE
What you mean NO? So the string I found is useless? YEs.
Damn.
return false
Assuming strlen does not iterate the whole string (but even in that case) this is not convenient at all.
for some reason ( I am a py newbie ... ) the -m call did not work ...
so here is a bash wrapper func ...
# ---------------------------------------------------------
# check the python synax for all the *.py files under the
# <<product_version_dir/sfw/python
# ---------------------------------------------------------
doCheckPythonSyntax(){
doLog "DEBUG START doCheckPythonSyntax"
test -z "$sleep_interval" || sleep "$sleep_interval"
cd $product_version_dir/sfw/python
# python3 -m compileall "$product_version_dir/sfw/python"
# foreach *.py file ...
while read -r f ; do \
py_name_ext=$(basename $f)
py_name=${py_name_ext%.*}
doLog "python3 -c \"import $py_name\""
# doLog "python3 -m py_compile $f"
python3 -c "import $py_name"
# python3 -m py_compile "$f"
test $! -ne 0 && sleep 5
done < <(find "$product_version_dir/sfw/python" -type f -name "*.py")
doLog "DEBUG STOP doCheckPythonSyntax"
}
# eof func doCheckPythonSyntax
I am processing a large collection of objects generated by our system; we changed the format of the stored data and needed to check each file, determine which ones were in the old format, and convert them. There are other ways to do this, but this one relates to your question.
ObjectListing list = amazonS3Client.listObjects(contentBucketName, contentKeyPrefix);
do {
List<S3ObjectSummary> summaries = list.getObjectSummaries();
for (S3ObjectSummary summary : summaries) {
String summaryKey = summary.getKey();
/* Retrieve object */
/* Process it */
}
list = amazonS3Client.listNextBatchOfObjects(list);
}while (list.isTruncated());
This is the simplest way
class YourSingletoneClass {
private static instance: YourSingletoneClass;
private constructor(public ifYouHaveAnyParams: string) {
}
static getInstance() {
if(!YourSingletoneClass.instance) {
YourSingletoneClass.instance = new YourSingletoneClass('If you have any params');
}
return YourSingletoneClass.instance;
}
}
I like to give my input field a border, remove the outline on focus, and "outline" the border instead:
input {
border: 1px solid grey;
&:focus {
outline: none;
border-left: 1px solid violet;
}
}
You can also do it with a transparent border:
input {
border: 1px solid transparent;
&:focus {
outline: none;
border-left: 1px solid violet;
}
}
May be this one help :)
DECLARE @SearchCriteria VARCHAR(25)
SET @SearchCriteria = 'employee'
IF CHARINDEX('%', @SearchCriteria) = 0
BEGIN
SET @SearchCriteria = '%' + @SearchCriteria + '%'
END
SELECT *
FROM Employee
WHERE Name LIKE @SearchCriteria
Be sure to find out your current working directory, and write your filepath relative to it.
This code:
File here = new File(".");
System.out.println(here.getAbsolutePath());
... will print out that directory.
Also, unrelated to your question, try to use File.separator
to remain OS-independent. Backslashes work only on Windows.
from msvcrt import getch
pos = [0, 0]
def fright():
global pos
pos[0] += 1
def fleft():
global pos
pos[0] -= 1
def fup():
global pos
pos[1] += 1
def fdown():
global pos
pos[1] -= 1
while True:
print'Distance from zero: ', pos
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
print('selected')
elif key == 32: #Space
print('jump')
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
print('down')
fdown
elif key == 72: #Up arrow
print('up')
fup()
elif key == 75: #Left arrow
print('left')
fleft()
elif key == 77: #Right arrow
print('right')
fright()
This is a more general answer meant to be a quick reference for future viewers.
Example
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Explanation from the documentation
table
String: The table name to compile the query against.columns
String: A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.selection
String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.selectionArgs
String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.groupBy
String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.having
String: A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.orderBy
String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.limit
String: Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
I solved it like this;
1.Created a function
export function FormatString(str: string, ...val: string[]) {
for (let index = 0; index < val.length; index++) {
str = str.replace(`{${index}}`, val[index]);
}
return str;
}
2.Used it like the following;
FormatString("{0} is {1} {2}", "This", "formatting", "hack");
The width attribute of <td>
is deprecated in HTML 5.
Use CSS. e.g.
<td style="width:100px">
in detail, like this:
<table >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td style="width:70%">January</td>
<td style="width:30%">$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
You Can try this script
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>
I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\
For example, your installer puts your dlls into:
\program files\<your app dir>\
or
\program files\common files\<your app name>\
(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)
and then sets a registry tag :
HKLM\software\<your app name>
-- dllLocation
The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.
The above is the smart way to go.
You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)
system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/
One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..
It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)
Like the docs say, think about it this way. If you were to do an application like a book reader, you will not want to load all the fragments into memory at once. You would like to load and destroy Fragments
as the user reads. In this case you will use FragmentStatePagerAdapter
. If you are just displaying 3 "tabs" that do not contain a lot of heavy data (like Bitmaps
), then FragmentPagerAdapter
might suit you well. Also, keep in mind that ViewPager
by default will load 3 fragments into memory. The first Adapter
you mention might destroy View
hierarchy and re load it when needed, the second Adapter
only saves the state of the Fragment
and completely destroys it, if the user then comes back to that page, the state is retrieved.
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.
For multiple files; note the newer "multiple" attribute for input:
Form:
@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label for="files">Filename:</label>
<input type="file" name="files" multiple="true" id="files" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
return View();
}
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');
You put it as =(B0+4)/($A$0)
You can also go across WorkSheets with Sheet1!$a$0
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
additionally, you need to dissmis dialog before calling activity.super.onBackPressed()
, otherwise you'll get "Activity has leaked.." error.
Example in my case with sweetalerdialog library:
@Override
public void onBackPressed() {
//super.onBackPressed();
SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
progressDialog.setCancelable(false);
progressDialog.setTitleText("Are you sure you want to exit?");
progressDialog.setCancelText("No");
progressDialog.setConfirmText("Yes");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
MainActivity.super.onBackPressed();
}
});
progressDialog.show();
}
WAMP stands for Windows,Apache,Mysql,Php
XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)
It is cross-platform software
It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.
it is easy to configure and use.
It is easy to Use. (Changing Configuration)
WAMP is Available for both 64 bit and 32-bit system.
if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.
i suggest using laragon :
Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.
Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.
Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.
Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.
Pretty URLs
Use app.test
instead of localhost/app
.
Portable
You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.
Isolated
Laragon has an isolated environment with your OS - it will keep your system clean.
Easy Operation
Unlike others which pre-config for you, Laragon auto-configsall
the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.
Modern & Powerful
Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed.
Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.
Yes. In fact Axel Schreiner provides his book "Object-oriented Programming in ANSI-C" for free which covers the subject quite thoroughly.
Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case:
to get extension of a given file absolute path, you can simply type:
filepath.rpartition('.')[-1]
example:
path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]
will give you: 'csv'
BEGIN TRANSACTION;
DECLARE @tblMapping table(sourceid int, destid int)
INSERT INTO [table1] ([data])
OUTPUT source.id, new.id
Select [data] from [external_table] source;
INSERT INTO [table2] ([table1_id], [data])
Select map.destid, source.[more data]
from [external_table] source
inner join @tblMapping map on source.id=map.sourceid;
COMMIT TRANSACTION;
<html>
<title>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>
<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
<!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->
<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
</asp:Repeater>
</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>
<script>
$(function () {
$('a').click(function() {
$(this).parent().children('.dataContentSectionMessages').slideToggle();
});
});
</script>
</html>
In my case I didn't add the http://
prefix. Potentially worth checking.
400 Bad Request is proper HTTP status code for your use case. The code is defined by HTTP/0.9-1.1 RFC.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
http://tools.ietf.org/html/rfc2616#section-10.4.1
422 Unprocessable Entity is defined by RFC 4918 - WebDav. Note that there is slight difference in comparison to 400, see quoted text below.
This error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
To keep uniform interface you should use 422 only in a case of XML responses and you should also support all status codes defined by Webdav extension, not just 422.
http://tools.ietf.org/html/rfc4918#page-78
See also Mark Nottingham's post on status codes:
it’s a mistake to try to map each part of your application “deeply” into HTTP status codes; in most cases the level of granularity you want to be aiming for is much coarser. When in doubt, it’s OK to use the generic status codes 200 OK, 400 Bad Request and 500 Internal Service Error when there isn’t a better fit.
The problem here is that SHA256Managed
reads 4096 bytes at a time (inherit from FileStream
and override Read(byte[], int, int)
to see how much it reads from the filestream), which is too small a buffer for disk IO.
To speed things up (2 minutes for hashing 2 Gb file on my machine with SHA256, 1 minute for MD5) wrap FileStream
in BufferedStream
and set reasonably-sized buffer size (I tried with ~1 Mb buffer):
// Not sure if BufferedStream should be wrapped in using block
using(var stream = new BufferedStream(File.OpenRead(filePath), 1200000))
{
// The rest remains the same
}
As mentioned in "Polling must die: triggering Jenkins builds from a git hook", you can notify Jenkins of a new commit:
With the latest Git plugin 1.1.14 (that I just release now), you can now do this more >easily by simply executing the following command:
curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>
This will scan all the jobs that’s configured to check out the specified URL, and if they are also configured with polling, it’ll immediately trigger the polling (and if that finds a change worth a build, a build will be triggered in turn.)
This allows a script to remain the same when jobs come and go in Jenkins.
Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn’t require authentication even for secured Jenkins, because the server doesn’t directly use anything that the client is sending. It runs polling to verify that there is a change, before it actually starts a build.
As mentioned here, make sure to use the right address for your Jenkins server:
since we're running Jenkins as standalone Webserver on port 8080 the URL should have been without the
/jenkins
, like this:http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git
To reinforce that last point, ptha adds in the comments:
It may be obvious, but I had issues with:
curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>.
The url parameter should match exactly what you have in Repository URL of your Jenkins job.
When copying examples I left out the protocol, in our casessh://
, and it didn't work.
You can also use a simple post-receive hook like in "Push based builds using Jenkins and GIT"
#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \
http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx
Configure your Jenkins job to be able to “Trigger builds remotely” and use an authentication token (
1qaz2wsx
in this example).
However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.
I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.
Basically, your build script can:
git notes
) on the first callHEAD
of your branch candidate for build and the commit referenced by the git notes
'build' (git show refs/notes/build
): git diff --name-only SHA_build HEAD
.git notes
'build
' to HEAD
.May 2016: cwhsu points out in the comments the following possible url:
you could just use
curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN
if you set trigger config in your item
June 2016, polaretto points out in the comments:
I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo namerepository=${PWD%/hooks}; repository=${repository##*/}
and then use it like:
curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository
JRE is a Run-Time Environment for running Java stuffs on your machine. What Eclipse needs is JDK as a Development Kit.
Install the latest JDK (and not JRE) from http://www.oracle.com/technetwork/pt/java/javase/downloads/jdk8-downloads-2133151.html and you should be good on Mac!
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.
I'm using Eclipse Kepler release. There is no Installation Details or About Eclipse menu item under help. For me, it was Help | Eclipse Marketplace...
I had to click on the "Installed" tab. The plug-in I wanted to remove was listed there, with an "Uninstall" option.
I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder
Update: there are two possible scenarios here:
You are determining if an object is a collection;
You are determining if a class is a collection.
The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection
or Map
will cover the Java Collections.
Solution 1:
public static boolean isCollection(Object ob) {
return ob instanceof Collection || ob instanceof Map;
}
Solution 2:
public static boolean isClassCollection(Class c) {
return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
}
(1) can also be implemented in terms of (2):
public static boolean isCollection(Object ob) {
return ob != null && isClassCollection(ob.getClass());
}
I don't think the efficiency of either method will be greatly different from the other.
If I remember correctly, the gen stands for generation, as in a generational garbage collector (that treats younger objects differently than mid-life and "permanent" objects). Principle of locality suggests that recently created objects will be wiped out first.
jackson-annotations provides @JsonFormat
which can handle a lot of customizations without the need to write the custom serializer.
For example, requesting a STRING
shape for a field with numeric type will output the numeric value as string
public class Person {
public String name;
public int age;
@JsonFormat(shape = JsonFormat.Shape.STRING)
public int favoriteNumber;
}
will result in the desired output
{"name":"Joe","age":25,"favoriteNumber":"123"}
If you are using Docker 1.12 or newer, just use SHELL
!
general:
SHELL ["/bin/bash", "-c"]
for python vituralenv:
SHELL ["/bin/bash", "-c", "source /usr/local/bin/virtualenvwrapper.sh"]
from https://docs.docker.com/engine/reference/builder/#shell
SHELL ["executable", "parameters"]
The SHELL instruction allows the default shell used for the shell form of commands to be overridden. The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]. The SHELL instruction must be written in JSON form in a Dockerfile.
The SHELL instruction is particularly useful on Windows where there are two commonly used and quite different native shells: cmd and powershell, as well as alternate shells available including sh.
The SHELL instruction can appear multiple times. Each SHELL instruction overrides all previous SHELL instructions, and affects all subsequent instructions. For example:
FROM microsoft/windowsservercore # Executed as cmd /S /C echo default RUN echo default # Executed as cmd /S /C powershell -command Write-Host default RUN powershell -command Write-Host default # Executed as powershell -command Write-Host hello SHELL ["powershell", "-command"] RUN Write-Host hello # Executed as cmd /S /C echo hello SHELL ["cmd", "/S"", "/C"] RUN echo hello
The following instructions can be affected by the SHELL instruction when the shell form of them is used in a Dockerfile: RUN, CMD and ENTRYPOINT.
The following example is a common pattern found on Windows which can be streamlined by using the SHELL instruction:
... RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" ...
The command invoked by docker will be:
cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt"
This is inefficient for two reasons. First, there is an un-necessary cmd.exe command processor (aka shell) being invoked. Second, each RUN instruction in the shell form requires an extra powershell -command prefixing the command.
To make this more efficient, one of two mechanisms can be employed. One is to use the JSON form of the RUN command such as:
... RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""] ...
While the JSON form is unambiguous and does not use the un-necessary cmd.exe, it does require more verbosity through double-quoting and escaping. The alternate mechanism is to use the SHELL instruction and the shell form, making a more natural syntax for Windows users, especially when combined with the escape parser directive:
# escape=` FROM microsoft/nanoserver SHELL ["powershell","-command"] RUN New-Item -ItemType Directory C:\Example ADD Execute-MyCmdlet.ps1 c:\example\ RUN c:\example\Execute-MyCmdlet -sample 'hello world'
Resulting in:
PS E:\docker\build\shell> docker build -t shell . Sending build context to Docker daemon 4.096 kB Step 1/5 : FROM microsoft/nanoserver ---> 22738ff49c6d Step 2/5 : SHELL powershell -command ---> Running in 6fcdb6855ae2 ---> 6331462d4300 Removing intermediate container 6fcdb6855ae2 Step 3/5 : RUN New-Item -ItemType Directory C:\Example ---> Running in d0eef8386e97 Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 10/28/2016 11:26 AM Example ---> 3f2fbf1395d9 Removing intermediate container d0eef8386e97 Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\ ---> a955b2621c31 Removing intermediate container b825593d39fc Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world' ---> Running in be6d8e63fe75 hello world ---> 8e559e9bf424 Removing intermediate container be6d8e63fe75 Successfully built 8e559e9bf424 PS E:\docker\build\shell>
The SHELL instruction could also be used to modify the way in which a shell operates. For example, using SHELL cmd /S /C /V:ON|OFF on Windows, delayed environment variable expansion semantics could be modified.
The SHELL instruction can also be used on Linux should an alternate shell be required such as zsh, csh, tcsh and others.
The SHELL feature was added in Docker 1.12.
Here is an example for toggling bold, underline, and italics.
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
if ( ActiveControl is RichTextBox r )
{
if ( keyData == ( Keys.Control | Keys.B ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.U ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.I ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
return true;
}
}
return base.ProcessCmdKey( ref msg, keyData );
}
It can also happen with varchar2 columns. This is pretty reproducible with PreparedStatements through JDBC by simply
So as above said it can be wrong with types, or column width exceeded.
Also note that as varchar2 allows 4k chars max, the real limit will be 2k for double byte chars
Hope this helps
For simple cases like here a static variable wrapped inside a static member function is nearly as good. It's simple and will usually be optimized away by compilers. This does not solve initialization order problem for complex objects though.
#include <iostream>
class MyClass
{
static const char * const letters(void){
static const char * const var = "abcdefghijklmnopqrstuvwxyz";
return var;
}
public:
void show(){
std::cout << letters() << "\n";
}
};
int main(){
MyClass c;
c.show();
}
You should use UNION if you want to combine different resultsets. Try the following:
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A)
UNION
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)
Yeah, I know I don't "have" to do it this way. But I usually write:
/* Return type (8/16/32/64 int size) is specified by argument size. */
template<class TYPE> inline TYPE BIT(const TYPE & x)
{ return TYPE(1) << x; }
template<class TYPE> inline bool IsBitSet(const TYPE & x, const TYPE & y)
{ return 0 != (x & y); }
E.g.:
IsBitSet( foo, BIT(3) | BIT(6) ); // Checks if Bit 3 OR 6 is set.
Amongst other things, this approach:
Weirdness is highly subjective, I just suggest to follow the official recommendation:
Guide to naming conventions on groupId, artifactId and version
groupId
will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.eg.
org.apache.maven
,org.apache.commons
A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.
eg.
org.apache.maven
,org.apache.maven.plugins
,org.apache.maven.reporting
artifactId
is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.eg.
maven
,commons-math
version
if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.eg.
2.0
,2.0.1
,1.3.1
The author of this question mentions that it’s usually only after
MySQL prints its output that he realises that the wrong query was executed.
As noted, in this case, Ctrl-C
doesn’t help. However, I’ve noticed that it
will abort the current query – if you catch it before any output is
printed. For example:
mysql> select * from jos_users, jos_comprofiler;
MySQL gets busy generating the Cartesian Product of the above two tables and
you soon notice that MySQL hasn't printed any output to screen (the process
state is Sending data) so you type Ctrl-C
:
Ctrl-C -- sending "KILL QUERY 113240" to server ...
Ctrl-C -- query aborted.
ERROR 1317 (70100): Query execution was interrupted
Ctrl-C
can similarly be used to stop an UPDATE
query.
For those of us on corporate networks using web filters that implement trusted man in the middle SSL solutions, it is necessary to add the web-filter certificate to the certifi cacert.pem.
A guide to doing this is here.
Main steps are:
I have to write a whole answer separately since it's hard to add a comment so long to the second answer.
I'm sorry to say this, but the second answer above doesn't work right.
The following three scenarios will show my point:
Scenario 1: Before the following way was deprecated,
$(window).load(function () {
alert("Window Loaded.");
});
if we execute the following two queries:
<script>
$(window).load(function () {
alert("Window Loaded.");
});
$(document).ready(function() {
alert("Dom Loaded.");
});
</script>,
the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the way it should be.
Scenario 2: But if we execute the following two queries like the second answer above suggests:
<script>
$(window).ready(function () {
alert("Window Loaded.");
});
$(document).ready(function() {
alert("Dom Loaded.");
});
</script>,
the alert (Window Loaded.) from the first query will show first, and the one (Dom Loaded.) from the second query will show later, which is NOT right.
Scenario 3: On the other hand, if we execute the following two queries, we'll get the correct result:
<script>
$(window).on("load", function () {
alert("Window Loaded.");
});
$(document).ready(function() {
alert("Dom Loaded.");
});
</script>,
that is to say, the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the RIGHT result.
In short, the FIRST answer is the CORRECT one:
$(window).on('load', function () {
alert("Window Loaded.");
});
Setting RetainSameConnection property to True for Excel manager Worked for me .
I had trouble using the accepted answer to access Shared Preference data across activities. In these steps, you give getSharedPreferences a name to access it.
Add the following dependency in the build.gradel (Module: app) file under Gradle Scripts:
implementation 'com.google.code.gson:gson:2.8.5'
To Save:
MyObject myObject = new MyObject;
//set variables of 'myObject', etc.
SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("Key", json);
prefsEditor.commit();
To Retrieve in a Different Activity:
SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("Key", "");
MyObject obj = gson.fromJson(json, MyObject.class);
you may use like that
System.out.println(Integer.decode("0x4d2")) // output 1234
//and vice versa
System.out.println(Integer.toHexString(1234); // output is 4d2);
Firstly Strings are immutable in java, you have to assign the result of the replace to a variable.
fieldName = fieldName.replace("watever","");
You can use also use regex as an option using String#replaceAll(regex, str)
;
fieldName = fieldName.replaceAll(",$","");
If tdd='<td class="abc"> 75</td>'
In Beautifulsoup
if(tdd.has_attr('class')):
print(tdd.attrs['class'][0])
Result: abc
I had this problem of no .env files showing up in the project.
Turns out the IDE I was using (Netbeans, try not to judge) will show certain types of .hidden files but not all.
After racking my brains for a bit I checked the file system and found the .env + .env.example files / modified them with a text editor.
Leaving this answer for the rare situation someones using a dodgy IDE like myself.
I verify XPath and CSS selectors using WebSync Chrome extension.
It provides possibility to verify selectors and also to generate/modify selectors by clicking on element attributes.
https://chrome.google.com/webstore/detail/natu-websync/aohpgnblncapofbobbilnlfliihianac
tempData.push( data[index] );
I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.
If you are using foreignkey then you have to use "on_delete=models.CASCADE" as it will eliminate the complexity developed after deleting the original element from the parent table. As simple as that.
categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)
Instead of an unneeded counter, now you have an unneeded list. Best solution is to use a variable that starts with "_", that tells syntax checkers that you are aware you are not using the variable.
x = range(5)
while x:
x.pop()
print "Work!"
A bit late but I thought I'd share in case it helps anyone: what is most likely the problem is simply that your Debug Console (the command line window that opens when run your project if it is a Windows Console Application
) is still open from the last time you ran the code. Just close that window, then rebuild and run: Ctrl + B
and F5
, respectively.
If you are using debug configuration for maven, use the command
clean install
And skip all the tests.
Scrolling an element requires changing its scrollTop
value over time. For a given point in time, calculate a new scrollTop
value. To animate smoothly, interpolate using a smooth-step algorithm.
Calculate scrollTop
as follows:
var point = smooth_step(start_time, end_time, now);
var scrollTop = Math.round(start_top + (distance * point));
Where:
start_time
is the time the animation started;end_time
is when the animation will end (start_time + duration)
;start_top
is the scrollTop
value at the beginning; anddistance
is the difference between the desired end value and the start value (target - start_top)
.A robust solution should detect when animating is interrupted, and more. Read my post about Smooth Scrolling without jQuery for details.
See the JSFiddle.
The code:
/**
Smoothly scroll element to the given target (element.scrollTop)
for the given duration
Returns a promise that's fulfilled when done, or rejected if
interrupted
*/
var smooth_scroll_to = function(element, target, duration) {
target = Math.round(target);
duration = Math.round(duration);
if (duration < 0) {
return Promise.reject("bad duration");
}
if (duration === 0) {
element.scrollTop = target;
return Promise.resolve();
}
var start_time = Date.now();
var end_time = start_time + duration;
var start_top = element.scrollTop;
var distance = target - start_top;
// based on http://en.wikipedia.org/wiki/Smoothstep
var smooth_step = function(start, end, point) {
if(point <= start) { return 0; }
if(point >= end) { return 1; }
var x = (point - start) / (end - start); // interpolation
return x*x*(3 - 2*x);
}
return new Promise(function(resolve, reject) {
// This is to keep track of where the element's scrollTop is
// supposed to be, based on what we're doing
var previous_top = element.scrollTop;
// This is like a think function from a game loop
var scroll_frame = function() {
if(element.scrollTop != previous_top) {
reject("interrupted");
return;
}
// set the scrollTop for this frame
var now = Date.now();
var point = smooth_step(start_time, end_time, now);
var frameTop = Math.round(start_top + (distance * point));
element.scrollTop = frameTop;
// check if we're done!
if(now >= end_time) {
resolve();
return;
}
// If we were supposed to scroll but didn't, then we
// probably hit the limit, so consider it done; not
// interrupted.
if(element.scrollTop === previous_top
&& element.scrollTop !== frameTop) {
resolve();
return;
}
previous_top = element.scrollTop;
// schedule next frame for execution
setTimeout(scroll_frame, 0);
}
// boostrap the animation process
setTimeout(scroll_frame, 0);
});
}
In PowerShell:
Add-AzureRmAccount #if not already logged in
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId
You got different things here:
First:
this
"
keyword). ref: angular.service vs angular.factory
Second:
Keep in mind all providers in AngularJS (value, constant, services, factories) are singletons!
Third:
Using one or the other (service or factory) is about code style. But, the common way in AngularJS is to use factory.
Why ?
Because "The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service."
(ref: http://www.amazon.com/Mastering-Web-Application-Development-AngularJS/dp/1782161821).
Service : Could be useful for sharing utility functions that are useful to invoke by simply appending ()
to the injected function reference. Could also be run with injectedArg.call(this)
or similar.
Factory : Could be useful for returning a ‘class’ function that can then be new`ed to create instances.
So, use a factory when you have complex logic in your service and you don't want expose this complexity.
In other cases if you want to return an instance of a service just use service.
But you'll see with time that you'll use factory in 80% of cases I think.
For more details: http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/
UPDATE :
Excellent post here : http://iffycan.blogspot.com.ar/2013/05/angular-service-or-factory.html
"If you want your function to be called like a normal function, use factory. If you want your function to be instantiated with the new operator, use service. If you don't know the difference, use factory."
UPDATE :
AngularJS team does his work and give an explanation: http://docs.angularjs.org/guide/providers
And from this page :
"Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions."
Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".
Press Ctrl+Shift+T in the code editor. It will show you popup with suggestion to create a test.
Mac OS: ? Cmd+Shift+T
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.
Instead of:
SELECT * FROM MyTable
You can use:
SELECT col1, colNew, col2, col3 FROM MyTable
You can't use delete
to remove an item from an array. This is only used to remove a property from an object.
You should use splice to remove an element from an array:
deleteMsg(msg:string) {
const index: number = this.data.indexOf(msg);
if (index !== -1) {
this.data.splice(index, 1);
}
}
The solution that worked for me was: dir > a.txt | type a.txt.
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:
function loadStyle(src) {
return new Promise(function (resolve, reject) {
let link = document.createElement('link');
link.href = src;
link.rel = 'stylesheet';
link.onload = () => resolve(link);
link.onerror = () => reject(new Error(`Style load error for ${src}`));
document.head.append(link);
});
}
You can implement it as follows:
window.onload = function () {
loadStyle("https://fonts.googleapis.com/css2?family=Raleway&display=swap")
.then(() => loadStyle("css/style.css"))
.then(() => loadStyle("css/icomoon.css"))
.then(() => {
alert('All styles are loaded!');
}).catch(err => alert(err));
}
It's really cool, right? This is a way to decide the priority of the styles using Promises.
To see a multi-style loading implementation see: https://stackoverflow.com/a/63936671/13720928
If you are using Rails 5 and above, the following solution will work.
#delete based on id
user_id = 50
User.find(id: user_id).delete_all
#delete based on condition
threshold_age = 20
User.where(age: threshold_age).delete_all
https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all
I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.
Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.
Hence, the following css class could do that:
@media (min-width: 768px) {
.dropdown-menu {
width: 300px !important; /* change the number to whatever that you need */
}
}
(I had used it in my web app.)
I recommend using:
#!/bin/bash
It's not 100% portable (some systems place bash
in a location other than /bin
), but the fact that a lot of existing scripts use #!/bin/bash
pressures various operating systems to make /bin/bash
at least a symlink to the main location.
The alternative of:
#!/usr/bin/env bash
has been suggested -- but there's no guarantee that the env
command is in /usr/bin
(and I've used systems where it isn't). Furthermore, this form will use the first instance of bash
in the current users $PATH
, which might not be a suitable version of the bash shell.
(But /usr/bin/env
should work on any reasonably modern system, either because env
is in /usr/bin
or because the system does something to make it work. The system I referred to above was SunOS 4, which I probably haven't used in about 25 years.)
If you need a script to run on a system that doesn't have /bin/bash
, you can modify the script to point to the correct location (that's admittedly inconvenient).
I've discussed the tradeoffs in greater depth in my answer to this question.
A somewhat obscure update: One system I use, Termux, a desktop-Linux-like layer that runs under Android, doesn't have /bin/bash
(bash
is /data/data/com.termux/files/usr/bin/bash
) -- but it has special handling to support #!/bin/bash
.
I had wrong package names:
main.java.hello
and main.test.hello
rather than com.blabla.hello
.
src/main/java
and created another src-folder src/test/java
.src/main/java
to com.blabla.hello
src/test/java
.Use the latest scope provided by Laravel out of the box.
Model::latest()->first();
That way you're not retrieving all the records. A nicer shortcut to orderBy.
The documentation explains it pretty well:
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.
As with all performance optimizations, it is a good idea to avoid optimizing things prematurely (i.e. without hard data on where the bottlenecks are).
Creating a reusable Line
component worked for me:
import React from 'react';
import { View } from 'react-native';
export default function Line() {
return (
<View style={{
height: 1,
backgroundColor: 'rgba(255, 255, 255 ,0.3)',
alignSelf: 'stretch'
}} />
)
}
Now, Import and use Line
anywhere:
<Line />
Classes
Modules
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
Only if you #include "stack.cpp
at the end of stack.hpp
. I'd only recommend this approach if the implementation is relatively large, and if you rename the .cpp file to another extension, as to differentiate it from regular code.
You might find useful mosaic
plot from statsmodels. Which can also give statistical highlighting for the variances.
from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);
But beware of the 0 sized cell - they will cause problems with labels.
See this answer for details
\b(?=\w)(?!(ma|(t){1}))\b(\w*)
this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines
String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);
In your eclipse.ini file simply put
–vm
/home/aniket/jdk1.7.0_11/bin(Your path to JDK 7)
before -vmargs
line.
Jérôme Petazzoni has a pretty interesting blog post on how to Attach a volume to a container while it is running. This isn't something that's built into Docker out of the box, but possible to accomplish.
As he also points out
This will not work on filesystems which are not based on block devices.
It will only work if /proc/mounts correctly lists the block device node (which, as we saw above, is not necessarily true).
Also, I only tested this on my local environment; I didn’t even try on a cloud instance or anything like that
YMMV
C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:
1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:
#define ROWS 4
#define COLS 5
void func(int array[ROWS][COLS])
{
int i, j;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
array[i][j] = i*j;
}
}
}
void func_vla(int rows, int cols, int array[rows][cols])
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int x[ROWS][COLS];
func(x);
func_vla(ROWS, COLS, x);
}
2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.
void func(int** array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int rows, cols, i;
int **x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * sizeof *x);
for (i=0; i<rows; i++)
{
x[i] = malloc(cols * sizeof *x[i]);
}
/* use the array */
func(x, rows, cols);
/* deallocate the array */
for (i=0; i<rows; i++)
{
free(x[i]);
}
free(x);
}
3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:
void func(int* array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i*cols+j]=i*j;
}
}
}
int main()
{
int rows, cols;
int *x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * cols * sizeof *x);
/* use the array */
func(x, rows, cols);
/* deallocate the array */
free(x);
}
4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);
void func_vla(int rows, int cols, int array[rows][cols])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = (i + 1) * (j + 1);
}
}
}
int main(void)
{
int rows, cols;
get_rows_cols(&rows, &cols);
int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
/* error check omitted */
func_vla(rows, cols, array);
dump_array("After initialization", rows, cols, array);
free(array);
return 0;
}
void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
{
printf("%s (%dx%d):\n", tag, rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%4d", array[i][j]);
putchar('\n');
}
}
void get_rows_cols(int *rows, int *cols)
{
srand(time(0)); // Only acceptable because it is called once
*rows = 5 + rand() % 10;
*cols = 3 + rand() % 12;
}
using jQuery:
$( ".myClass" ).load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
Try one of the following, depending on your image format:
UIImageJPEGRepresentation
Returns the data for the specified image in JPEG format.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
UIImagePNGRepresentation
Returns the data for the specified image in PNG format
NSData * UIImagePNGRepresentation (
UIImage *image
);
EDIT:
if you want to access the raw bytes that make up the UIImage, you could use this approach:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];
This will give you the low-level representation of the image RGB pixels.
(Omit the CFBridgingRelease
bit if you are not using ARC).
The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:
% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
extracting ikernel.dll
extracting IsProBENT.tlb
....
extracting IScript.dll
extracting iKernel.rgs
All done, no errors.
Working with just one selector:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
Just in case you were wondering how to rename columns during aggregation, here's how for
df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')
Or,
df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))
MySum MyCount
Company Name
Vifor Pharma UK Ltd 4207.93 5
As soon as the page loads, the init
function is fired and the page is redirected:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script>
function init()
{
window.location.href = "www.wherever.com";
}
</script>
</head>
<body onload="init()">
</body>
</html>
I was experiencing this same error, and spent forever adding the suggested startup statements to various config files in my solution, attempting to isolate the framework mismatch. Nothing worked. I also added startup information to my XML schemas. That didn't help either. Looking at the actual file that was causing the problem (which would only say it was "moved or deleted") revealed it was actually the License Compiler (LC).
Deleting the offending licenses.licx file seems to have fixed the problem.
Keeping it simple:
// Generator
function* iter(a, b, step = 1) {
for (let i = b ? a : 0; i < (b || a); i += step) {
yield i
}
}
const range = (a, b, step = 1) =>
typeof a === 'string'
? [...iter(a.charCodeAt(), b.charCodeAt() + 1)].map(n => String.fromCharCode(n))
: [...iter(a, b, step)]
range(4) // [0, 1, 2, 3]
range(1, 4) // [1, 2, 3]
range(2, 20, 3) // [2, 5, 8, 11, 14, 17]
range('A', 'C') // ['A', 'B', 'C']
Now days, for the expected result, display:grid;
would do (be the easiest ?):
ul {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
_x000D_
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
_x000D_
you can also get the columns shrinking on the left and able to have different width:
ul {
display: grid;
grid-template-columns: repeat(2, auto);
justify-content: start;
}
li {
margin-left: 1em;
border: solid 1px;/*see me */
}
_x000D_
<ul>
<li>A</li>
<li>B</li>
<li>C 123456</li>
<li>D</li>
<li>E</li>
</ul>
_x000D_
for cakephp 2.0 Write this function in AppModel.php
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
To use this in Controller Write : echo $this->YourModelName->getLastQuery();
I have a single checkbox named chkDueDate
and an HTML object with a click event as follows:
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
Clicking the HTML object (in this case a <span>
) toggles the checked property of the checkbox.
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
You have some files locally that need to be merged before you can pull. You could checkout the files and then pull to overwrite your local files.
git checkout app/config/app.php app/config/database.php app/routes.php
git pull origin master
I was using export class TestCalendar implements OnInit{}
but i did not write the function
ngOnInit() {
/* Display initial */
}
. After running the command ng serve
, i found out that i was not using ngOnInit(){}
. Once i implemented, it started working fine. Hope it helps someone.
Better with kotlin extension functions
inline fun View.waitForLayout(crossinline yourAction: () -> Unit) {
val vto = viewTreeObserver
vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
when {
vto.isAlive -> {
vto.removeOnGlobalLayoutListener(this)
yourAction()
}
else -> viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
to read first line using bash, use read
statement. eg
read -r firstline<file
firstline
will be your variable (No need to assign to another)
From "What’s New in Python 2.6 - Interpreter Changes":
Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the
sys.dont_write_bytecode
variable, and Python code can change the value to modify the interpreter’s behaviour.
Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with .pyc
files by introducing a special __pycache__
subfolder, see What's New in Python 3.2 - PYC Repository Directories.
You need to turn it on its head in terms of the way you're thinking about it. Instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. This is exactly the same way you would find an item in a regular list in .NET.
There are two ways of doing this using LINQ, one uses query syntax and the other uses method syntax. Essentially, they are the same and could be used interchangeably depending on your preference:
Query Syntax:
var selected = from u in users
where new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights)
select u
foreach(user u in selected)
{
//Do your stuff on each selected user;
}
Method Syntax:
var selected = users.Where(u => new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights));
foreach(user u in selected)
{
//Do stuff on each selected user;
}
My personal preference in this instance might be method syntax because instead of assigning the variable, I could do the foreach over an anonymous call like this:
foreach(User u in users.Where(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
//Do stuff on each selected user;
}
Syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.
It all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.
An alternative way doesn't even use LINQ, you can use the same method syntax replacing "where" with "FindAll" and get the same result, which will also work in .NET 2.0:
foreach(User u in users.FindAll(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
//Do stuff on each selected user;
}
The problem might be in the rest of the html, the part that you didn't post.
With this example (I just closed the open tags):
<a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
<p>
<strong class="ng-binding">Smoke Sequential</strong>
</p>
</div>
</div>
</a>
I was able to find the element without trouble with:
driver.findElement(By.linkText("Smoke Sequential")).click();
If there is more text inside the element, you could try a find by partial link text:
driver.findElement(By.partialLinkText("Sequential")).click();
You can add comments in Vim's configuration file by either:
" brief descriptiion of command
or:
"" commended command
Taken from here
Try this
self.opener.location.reload();
Open the parent of a current window and reload the location.
Set objFSO=CreateObject("Scripting.FileSystemObject")
' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close
'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
Wscript.Echo strLine
Loop
objFile.Close
'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)
Yes, here you can use LIMIT
.
You can try it by the below query:
SELECT * FROM employee_list SORT BY salary DESC LIMIT 2
You can use either of the following:
include "class.twitter.php";
or
require "class.twitter.php";
Using require
(or require_once
if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include
will only raise a warning. See http://php.net/require and http://php.net/include for more details
I think this would work
moment().weekday(); //if today is thursday it will return 4
Java 8: Use random generator isolated to the current thread: ThreadLocalRandom nextBoolean()
Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.
java.util.concurrent.ThreadLocalRandom.current().nextBoolean();
SELECT product FROM Your_table_name WHERE Product LIKE '%XYZ%';
The above statement will show result from a single table. If you want to add more tables then simply use the UNION statement.
SELECT product FROM Table_name_1
WHERE Product LIKE '%XYZ%'
UNION
SELECT product FROM Table_name_2
WHERE Product LIKE '%XYZ%'
UNION
SELECT product FROM Table_name_3
WHERE Product LIKE '%XYZ%'
... and so on
Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index
type to keep array's indexes from end:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
You can use this index to get last array value in any lenght of array. For example:
var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5
For more information check documentation
I just created my own version using CSS. As I need to disabled, then when document is ready use jQuery to make active. So that way a user cannot click on a button until after the document is ready. So i can substitute with AJAX instead. The way I came up with, was to add a class to the anchor tag itself and remove the class when document is ready. Could re-purpose this for your needs.
CSS:
a.disabled{
pointer-events: none;
cursor: default;
}
HTML:
<a class="btn btn-info disabled">Link Text</a>
JS:
$(function(){
$('a.disabled').on('click',function(event){
event.preventDefault();
}).removeClass('disabled');
});
This was working for me on values/styles.xml
add items:
`<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>`
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
The following selects all descendant elements and disables them:
$("#dcacl").find("*").prop("disabled", true);
But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:
$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);
To re-enable you just set "disabled" to false.
I want to Disable them at loading the page and then by a click i can enable them
OK, so put the above code in a document ready handler, and setup an appropriate click handler:
$(document).ready(function() {
var $dcac1kids = $("#dcac1").find(":input");
$dcac1kids.prop("disabled",true);
// not sure what you want to click on to re-enable
$("selector for whatever you want to click").one("click",function() {
$dcac1kids.prop("disabled",false);
}
}
I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one()
since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one()
to .click()
if appropriate.
If you want the world to be a two-valued boolean place, you must prevent the null (third value) case yourself.
Don't write IN clauses that allow nulls in the list side. Filter them out!
common_id not in
(
select common_id from Table1
where common_id is not null
)
From comments:
But, this code never stops (because of integer overflow) !?! Yves Daoust
For many numbers it will not overflow.
If it will overflow - for one of those unlucky initial seeds, the overflown number will very likely converge toward 1 without another overflow.
Still this poses interesting question, is there some overflow-cyclic seed number?
Any simple final converging series starts with power of two value (obvious enough?).
2^64 will overflow to zero, which is undefined infinite loop according to algorithm (ends only with 1), but the most optimal solution in answer will finish due to shr rax
producing ZF=1.
Can we produce 2^64? If the starting number is 0x5555555555555555
, it's odd number, next number is then 3n+1, which is 0xFFFFFFFFFFFFFFFF + 1
= 0
. Theoretically in undefined state of algorithm, but the optimized answer of johnfound will recover by exiting on ZF=1. The cmp rax,1
of Peter Cordes will end in infinite loop (QED variant 1, "cheapo" through undefined 0
number).
How about some more complex number, which will create cycle without 0
?
Frankly, I'm not sure, my Math theory is too hazy to get any serious idea, how to deal with it in serious way. But intuitively I would say the series will converge to 1 for every number : 0 < number, as the 3n+1 formula will slowly turn every non-2 prime factor of original number (or intermediate) into some power of 2, sooner or later. So we don't need to worry about infinite loop for original series, only overflow can hamper us.
So I just put few numbers into sheet and took a look on 8 bit truncated numbers.
There are three values overflowing to 0
: 227
, 170
and 85
(85
going directly to 0
, other two progressing toward 85
).
But there's no value creating cyclic overflow seed.
Funnily enough I did a check, which is the first number to suffer from 8 bit truncation, and already 27
is affected! It does reach value 9232
in proper non-truncated series (first truncated value is 322
in 12th step), and the maximum value reached for any of the 2-255 input numbers in non-truncated way is 13120
(for the 255
itself), maximum number of steps to converge to 1
is about 128
(+-2, not sure if "1" is to count, etc...).
Interestingly enough (for me) the number 9232
is maximum for many other source numbers, what's so special about it? :-O 9232
= 0x2410
... hmmm.. no idea.
Unfortunately I can't get any deep grasp of this series, why does it converge and what are the implications of truncating them to k bits, but with cmp number,1
terminating condition it's certainly possible to put the algorithm into infinite loop with particular input value ending as 0
after truncation.
But the value 27
overflowing for 8 bit case is sort of alerting, this looks like if you count the number of steps to reach value 1
, you will get wrong result for majority of numbers from the total k-bit set of integers. For the 8 bit integers the 146 numbers out of 256 have affected series by truncation (some of them may still hit the correct number of steps by accident maybe, I'm too lazy to check).
This works well
Seems that no one mentioned Query Express (http://www.albahari.com/queryexpress.aspx) and a fork Query ExPlus (also link at the bottom of http://www.albahari.com/queryexpress.aspx)
BTW. First URL is the home page of Joseph Albahari who is the author of LINQPad (check out this killer tool)
From react docs Passing arguments to event handlers
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
Here's an example of how you would accomplish such a task:
#import <Foundation/Foundation.h>
typedef int (^IntBlock)();
@interface myobj : NSObject
{
IntBlock compare;
}
@property(readwrite, copy) IntBlock compare;
@end
@implementation myobj
@synthesize compare;
- (void)dealloc
{
// need to release the block since the property was declared copy. (for heap
// allocated blocks this prevents a potential leak, for compiler-optimized
// stack blocks it is a no-op)
// Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
[compare release];
[super dealloc];
}
@end
int main () {
@autoreleasepool {
myobj *ob = [[myobj alloc] init];
ob.compare = ^
{
return rand();
};
NSLog(@"%i", ob.compare());
// if not ARC
[ob release];
}
return 0;
}
Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)()
. If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id)
, and change your block to:
^ (id obj1, id obj2)
{
return rand();
};
I hope this helps.
EDIT March 12, 2012:
For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.
For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html
When you say "called" I'm going to assume you mean an ID tag.
To make it cross-brower, I wouldn't suggest using the CSS3 []
, although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".
Then:
#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }
This assumes you are using the same classes elsewhere, if not, this will suffice:
.tb { width: 150px }
.rb { width: 20px }
As @David mentioned, to access anything within the division itself:
#divContainer [element] { ... }
Where [element] is whatever HTML element you need.
During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.
You can make your constructor private
or internal
if you want, just so long as it's parameterless.
You don't need to download any new software. You can use Octave Online to open .m files.
I think this will work, if you are using JodaTime:
String strDateTime = "11/15/2013 08:00:00";
DateTime dateTime = DateTime.parse(strDateTime);
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/YYYY");
String strDateOnly = fmt.print(dateTime);
I got part of this from here.
You can load jpeg binary data as a file and parse the jpeg headers yourself. The one you are looking for is the 0xFFC0 or Start of Frame header:
Start of frame marker (FFC0)
* the first two bytes, the length, after the marker indicate the number of bytes, including the two length bytes, that this header contains
* P -- one byte: sample precision in bits (usually 8, for baseline JPEG)
* Y -- two bytes
* X -- two bytes
* Nf -- one byte: the number of components in the image
o 3 for color baseline JPEG images
o 1 for grayscale baseline JPEG images
* Nf times:
o Component ID -- one byte
o H and V sampling factors -- one byte: H is first four bits and V is second four bits
o Quantization table number-- one byte
The H and V sampling factors dictate the final size of the component they are associated with. For instance, the color space defaults to YCbCr and the H and V sampling factors for each component, Y, Cb, and Cr, default to 2, 1, and 1, respectively (2 for both H and V of the Y component, etc.) in the Jpeg-6a library by the Independent Jpeg Group. While this does mean that the Y component will be twice the size of the other two components--giving it a higher resolution, the lower resolution components are quartered in size during compression in order to achieve this difference. Thus, the Cb and Cr components must be quadrupled in size during decompression.
For more info about the headers check out wikipedia's jpeg entry or I got the above info here.
I used a method similar to the code below which I got from this post at the sun forums:
import java.awt.Dimension;
import java.io.*;
public class JPEGDim {
public static Dimension getJPEGDimension(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
// check for SOI marker
if (fis.read() != 255 || fis.read() != 216)
throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");
Dimension d = null;
while (fis.read() == 255) {
int marker = fis.read();
int len = fis.read() << 8 | fis.read();
if (marker == 192) {
fis.skip(1);
int height = fis.read() << 8 | fis.read();
int width = fis.read() << 8 | fis.read();
d = new Dimension(width, height);
break;
}
fis.skip(len - 2);
}
fis.close();
return d;
}
public static void main(String[] args) throws IOException {
System.out.println(getJPEGDimension(new File(args[0])));
}
}
In ssms we can use GO to execute same statement
Edit This mean if you put
some query
GO n
Some query will be executed n times
The Bundle
is a container for all the information you want to save. You use the put* functions to insert data into it. Here's a short list (there are more) of put functions you can use to store data in the Bundle
.
putString
putBoolean
putByte
putChar
putFloat
putLong
putShort
putParcelable (used for objects but they must implement Parcelable)
In your onCreate
function, this Bundle
is handed back to the program. The best way to check if the application is being reloaded, or started for the first time is:
if (savedInstanceState != null) {
// Then the application is being reloaded
}
To get the data back out, use the get* functions just like the put* functions. The data is stored as a name-value pair. This is like a hashmap. You provide a key and the value, then when you want the value back, you give the key and the function gets the value. Here's a short example.
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("message", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String message = savedInstanceState.getString("message");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Your saved message will be toasted to the screen. Hope this helps.
What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80>
and https <VirtualHost *:443>
virtual host blocks:
ServerName your-app.com
ServerAlias www.your-app.com
Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"
The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options
header so we need to first always remove the default value, in my case it was DENY
, and then with the next rule we set it to the desired value, in my case SAMEORIGIN
. Of course you can use the Header set X-Frame-Options ALLOW-FROM ...
rule as well.
Laravel provides bunch of helper functions and for your requirement you can simply
use url() function of Laravel Helpers
but in case of Laravel 5.2 you will have to use url('/')
here is the list of all other helper functions of Laravel
I've just created a javascript shim to achieve this goal. Take a look if you want, it's a proof-of-concept, but take care: it's a early version and still needs some work.
Make file executable:
chmod +x file
Find location of perl:
which perl
This should return something like
/bin/perl sometimes /usr/local/bin
Then in the first line of your script add:
#!"path"/perl with path from above e.g.
#!/bin/perl
Then you can execute the file
./file
There may be some issues with the PATH, so you may want to change that as well ...
The server may need read permission for your home directory and .htaccess therein