require 'alien'
if alien.platform == "windows" then
kernel32 = alien.load("kernel32.dll")
sleep = kernel32.Sleep
sleep:types{ret="void",abi="stdcall","uint"}
else
-- untested !!!
libc = alien.default
local usleep = libc.usleep
usleep:types('int', 'uint')
sleep = function(ms)
while ms > 1000 do
usleep(1000)
ms = ms - 1000
end
usleep(1000 * ms)
end
end
print('hello')
sleep(500) -- sleep 500 ms
print('world')
I had a similar problem (trying to start a Jenkins slave agent on Windows) on Windows 2008R2
, Java 1.7.0_15
I had two situations that contributed to the problem and that changing both of them fixed it:
1) Installing Java
in a unix
-compatible path (changing from c:\Program Files\... to c:\Software\...
); I don't think this directly affected the problem described in this thread, but noting the change;
2) Running Java
not through a shortcut. It originally failed with a shortcut, but re-running
from the direct executable (C:\Software\Java...\bin\java
) worked.
You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.
See http://docs.python.org/release/2.3/lib/module-string.html
You can use the GetStringAsync
method:
var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);
A good answer was already posted, this is only a recommendation!
A good way would be to just add a category to NSManagedObject
and implement a method like I did:
Header File (e.g. NSManagedObject+Ext.h
)
@interface NSManagedObject (Logic)
+ (void) deleteAllFromEntity:(NSString*) entityName;
@end
Code File: (e.g. NSManagedObject+Ext.m)
@implementation NSManagedObject (Logic)
+ (void) deleteAllFromEntity:(NSString *)entityName {
NSManagedObjectContext *managedObjectContext = [AppDelegate managedObjectContext];
NSFetchRequest * allRecords = [[NSFetchRequest alloc] init];
[allRecords setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]];
[allRecords setIncludesPropertyValues:NO];
NSError * error = nil;
NSArray * result = [managedObjectContext executeFetchRequest:allRecords error:&error];
for (NSManagedObject * profile in result) {
[managedObjectContext deleteObject:profile];
}
NSError *saveError = nil;
[managedObjectContext save:&saveError];
}
@end
... the only thing you have to is to get the managedObjectContext from the app delegate, or where every you have it in ;)
afterwards you can use it like:
[NSManagedObject deleteAllFromEntity:@"EntityName"];
one further optimization could be that you remove the parameter for tha entityname and get the name instead from the clazzname. this would lead to the usage:
[ClazzName deleteAllFromEntity];
a more clean impl (as category to NSManagedObjectContext):
@implementation NSManagedObjectContext (Logic)
- (void) deleteAllFromEntity:(NSString *)entityName {
NSFetchRequest * allRecords = [[NSFetchRequest alloc] init];
[allRecords setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self]];
[allRecords setIncludesPropertyValues:NO];
NSError * error = nil;
NSArray * result = [self executeFetchRequest:allRecords error:&error];
for (NSManagedObject * profile in result) {
[self deleteObject:profile];
}
NSError *saveError = nil;
[self save:&saveError];
}
@end
The usage then:
[managedObjectContext deleteAllFromEntity:@"EntityName"];
From the documentation of InetAddress.getByName(String host)
:
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
So you can use it.
typeof(T).Name;
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
You do with this too...
.p{
writing-mode: vertical-rl;
text-orientation: upright;
}
The Bash builtin getopts function can be used to parse long options by putting a dash character followed by a colon into the optspec:
#!/usr/bin/env bash
optspec=":hv-:"
while getopts "$optspec" optchar; do
case "${optchar}" in
-)
case "${OPTARG}" in
loglevel)
val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
;;
loglevel=*)
val=${OPTARG#*=}
opt=${OPTARG%=$val}
echo "Parsing option: '--${opt}', value: '${val}'" >&2
;;
*)
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
echo "Unknown option --${OPTARG}" >&2
fi
;;
esac;;
h)
echo "usage: $0 [-v] [--loglevel[=]<value>]" >&2
exit 2
;;
v)
echo "Parsing option: '-${optchar}'" >&2
;;
*)
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
echo "Non-option argument: '-${OPTARG}'" >&2
fi
;;
esac
done
After copying to executable file name=getopts_test.sh
in the current working directory, one can produce output like
$ ./getopts_test.sh
$ ./getopts_test.sh -f
Non-option argument: '-f'
$ ./getopts_test.sh -h
usage: code/getopts_test.sh [-v] [--loglevel[=]<value>]
$ ./getopts_test.sh --help
$ ./getopts_test.sh -v
Parsing option: '-v'
$ ./getopts_test.sh --very-bad
$ ./getopts_test.sh --loglevel
Parsing option: '--loglevel', value: ''
$ ./getopts_test.sh --loglevel 11
Parsing option: '--loglevel', value: '11'
$ ./getopts_test.sh --loglevel=11
Parsing option: '--loglevel', value: '11'
Obviously getopts neither performs OPTERR
checking nor option-argument parsing for the long options. The script fragment above shows how this may be done manually. The basic principle also works in the Debian Almquist shell ("dash"). Note the special case:
getopts -- "-:" ## without the option terminator "-- " bash complains about "-:"
getopts "-:" ## this works in the Debian Almquist shell ("dash")
Note that, as GreyCat from over at http://mywiki.wooledge.org/BashFAQ points out, this trick exploits a non-standard behaviour of the shell which permits the option-argument (i.e. the filename in "-f filename") to be concatenated to the option (as in "-ffilename"). The POSIX standard says there must be a space between them, which in the case of "-- longoption" would terminate the option-parsing and turn all longoptions into non-option arguments.
dir /s *foo*
searches in current folder and sub folders.
It finds directories as well as files.
where /s means(documentation):
/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.
If you change your property to use a backing field (instead of an automatic property), you can do the following:
public event EventHandler ImageFullPath1Changed;
private string _imageFullPath1 = string.Empty;
public string ImageFullPath1
{
get
{
return imageFullPath1 ;
}
set
{
if (_imageFullPath1 != value)
{
_imageFullPath1 = value;
EventHandler handler = ImageFullPathChanged;
if (handler != null)
handler(this, e);
}
}
}
switch ((i != null) ? i : DEFAULT_VALUE) {
//...
}
If the user doesn't have Chrome, it will throw an exception like this:
//chrome.exe http://xxx.xxx.xxx --incognito
//chrome.exe http://xxx.xxx.xxx -incognito
//chrome.exe --incognito http://xxx.xxx.xxx
//chrome.exe -incognito http://xxx.xxx.xxx
private static void Chrome(string link)
{
string url = "";
if (!string.IsNullOrEmpty(link)) //if empty just run the browser
{
if (link.Contains('.')) //check if it's an url or a google search
{
url = link;
}
else
{
url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
}
}
try
{
Process.Start("chrome.exe", url + " --incognito");
}
catch (System.ComponentModel.Win32Exception e)
{
MessageBox.Show("Unable to find Google Chrome...",
"chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
You are calling nextInt
statically by using Random.nextInt
.
Instead, create a variable, Random r = new Random();
and then call r.nextInt(10)
.
It would be definitely worth while to check out:
You really should replace this line,
Random Random = new Random();
with something like this,
Random r = new Random();
If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:
private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
URL url = new URL(thisUrl);
builder = new Uri.Builder()
.scheme(url.getProtocol())
.authority(url.getAuthority())
.appendPath(url.getPath());
return builder.build();
}
var getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
I had a same issue on ubuntu 14.04 Here is a solution
sudo service docker start
or you can list images
docker images
Use IPython display to render PIL images in a notebook.
from PIL import Image # to load images
from IPython.display import display # to display images
pil_im = Image.open('path/to/image.jpg')
display(pil_im)
In case someone is using git svn, I had the same problem but could not remove the file since it was not there!. After checking permissions, touching the file and deleting it, and I don't remember what else, this did the trick:
If anyone want that also for multiple calendars its not very hard to add this functionallity to jquery ui. with minified search for:
x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&C==0?c?f:n:"")+(
add this in front of x
var accl = ''; if(this._get(a,"justMonth")) {accl = ' ui-datepicker-just_month';}
search for
<table class="ui-datepicker-calendar
and replace it with
<table class="ui-datepicker-calendar'+accl+'
also search for
this._defaults={
replace it with
this._defaults={justMonth:false,
for css you should use:
.ui-datepicker table.ui-datepicker-just_month{
display: none;
}
after that all is done just go to your desired datepicker init functions and provide setting var
$('#txt_month_chart_view').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
justMonth: true,
create: function(input, inst) {
$(".ui-datepicker table").addClass("badbad");
},
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
justMonth: true
is the key here :)
in command line first reach the directory where psql is present then write commands like this:
psql [database name] [username]
and then press enter psql asks for password give the user password:
then write
> \i [full path and file name with extension]
then press enter insertion done.
Update: while this answer was likely correct back in early 2013, it should not be used anymore. The proper solution uses offsets.
As for other users suggestion there are also native bootstrap classes available like:
class="text-center"
class="pagination-centered"
thanks to @Henning and @trejder
In essence, many things can go wrong in a multi threaded environment (instructions reordering, partially constructed objects, same variable having different values in different threads because of caching at the CPU level etc.).
I like the definition given by Java Concurrency in Practice:
A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
By correctly they mean that the program behaves in compliance with its specifications.
Contrived example
Imagine that you implement a counter. You could say that it behaves correctly if:
counter.next()
never returns a value that has already been returned before (we assume no overflow etc. for simplicity)A thread safe counter would behave according to those rules regardless of how many threads access it concurrently (which would typically not be the case of a naive implementation).
IQueryable is faster than IEnumerable if we are dealing with huge amounts of data from database because,IQueryable gets only required data from database where as IEnumerable gets all the data regardless of the necessity from the database
This type of question has been asked previously.
The type of sorting you are talking about is called "Natural Sorting". The data on which you want to do sort is alphanumeric. It would be better to create a new column for sorting.
For further help check natural-sort-in-mysql
check your project build in jdk 9 or not above that eclipse is having some issues with the modules. Change it to jdk 9 then it will run fine
If you want to copy a line to the clipboard you can also use the trick:
Ctrl-Alt-Down followed by Ctrl-X
The drawback is that the file where you copy the line from becomes dirty.
If I understand your question, here's one way. Say you have:
a = [4.1, 6.21, 1.0]
so here's some code...
def array_in_array(scalarlist):
return [(x,) for x in scalarlist]
Which leads to:
In [72]: a = [4.1, 6.21, 1.0]
In [73]: a
Out[73]: [4.1, 6.21, 1.0]
In [74]: def array_in_array(scalarlist):
....: return [(x,) for x in scalarlist]
....:
In [75]: b = array_in_array(a)
In [76]: b
Out[76]: [(4.1,), (6.21,), (1.0,)]
you need to reconfigure your tnsnames.ora so that it can point to your hostname after that listener will be able to pick the new hostname. after which check the status of your listener lsnrctl status and start listener lsnrctl start then register your listener. Alter system register
Seems that you need classmethod:
class World(object):
allAirports = []
@classmethod
def initialize(cls):
if not cls.allAirports:
f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
file_reader = csv.reader(f)
for col in file_reader:
cls.allAirports.append(Airport(col[0],col[2],col[3]))
return cls.allAirports
This alternate approach with filtering for format counts all available grub kernel modules:
ls -l /boot/grub/*.mod | wc -l
To solve this issue you need below three steps:
Set page encoding to UTF-8 like below:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8" %>
Set filter in web.xml file as below:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Set resource encoding to UTF-8, in case if you are writing any UTF-8 characters in Java code or JSP directly.
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href
attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
a less expensive and reusable method
function get_post_id_by_name( $post_name, $post_type = 'post' )
{
$post_ids = get_posts(array
(
'post_name' => $post_name,
'post_type' => $post_type,
'numberposts' => 1,
'fields' => 'ids'
));
return array_shift( $post_ids );
}
use DBName
select * from TABLE_NAME A
where A.date >= '2018-06-26 21:24' and A.date <= '2018-06-26 21:28';
date("Y-m-d",strtotime("last day of +1 month",strtotime($anydate)))
You just need to find the right multiplier, which can be easily calculated from the hist
object.
myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist)
lines(mydensity)
A more complete version, with a normal density and lines at each standard deviation away from the mean (including the mean):
myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist)
lines(mydensity)
myx <- seq(min(mtcars$mpg), max(mtcars$mpg), length.out= 100)
mymean <- mean(mtcars$mpg)
mysd <- sd(mtcars$mpg)
normal <- dnorm(x = myx, mean = mymean, sd = mysd)
lines(myx, normal * multiplier[1], col = "blue", lwd = 2)
sd_x <- seq(mymean - 3 * mysd, mymean + 3 * mysd, by = mysd)
sd_y <- dnorm(x = sd_x, mean = mymean, sd = mysd) * multiplier[1]
segments(x0 = sd_x, y0= 0, x1 = sd_x, y1 = sd_y, col = "firebrick4", lwd = 2)
If you want to pass with "arguments" a few others, you have to create the array of all arguments together, i.e. like this:
var Log = {
log: function() {
var args = ['myarg here'];
for(i=0; i<arguments.length; i++) args = args.concat(arguments[i]);
console.log.apply(this, args);
}
}
The question is bigger than just using wither static_cast or C style casting because there are different things that happen when using C style casts. The C++ casting operators are intended to make these operations more explicit.
On the surface static_cast and C style casts appear to the same thing, for example when casting one value to another:
int i;
double d = (double)i; //C-style cast
double d2 = static_cast<double>( i ); //C++ cast
Both of these cast the integer value to a double. However when working with pointers things get more complicated. some examples:
class A {};
class B : public A {};
A* a = new B;
B* b = (B*)a; //(1) what is this supposed to do?
char* c = (char*)new int( 5 ); //(2) that weird?
char* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error
In this example (1) maybe OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what a actually points to? (2) maybe perfectly legal(you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3). The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.
So, for strict "value casting" you can use static_cast. If you want run-time polymorphic casting of pointers use dynamic_cast. If you really want to forget about types, you can use reintrepret_cast. And to just throw const out the window there is const_cast.
They just make the code more explicit so that it looks like you know what you were doing.
For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.
var cssAnimate = function(cssClass, callback) {
var self = this;
// Checks if correct animation has ended
var setAnimationListener = function() {
self.one(
"webkitAnimationEnd oanimationend msAnimationEnd animationend",
function(e) {
if(
e.originalEvent.animationName == cssClass &&
e.target === e.currentTarget
) {
callback();
} else {
setAnimationListener();
}
}
);
}
self.addClass(cssClass);
setAnimationListener();
}
I used it kinda like this
cssAnimate.call($("#something"), "fadeIn", function() {
console.log("Animation is complete");
// Remove animation class name?
});
Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/
And this seems handy: http://api.jqueryui.com/addClass/
Update
After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.
OS X
If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.
Install Vim:
brew install vim --with-lua --with-override-system-vi
Install the GUI version of Vim:
brew install macvim --with-lua --with-override-system-vi
Restart the terminal for it to take effect.
Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can copy the line in Vim with yy
and paste it system-wide.
This is the best and easiest code:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.
You can download the zip. And then create a package
in your project with org.json as name. and paste all the downloaded codes there, and have fun.
I feel this to be the best and the most easiest JSON Decoding.
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :
The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.
//as I understand it, the "this" denotes the current view(focus) in the android program
No, "this" will only work if your MainActivity
referenced by this
implements the View.OnClickListener
, which is the parameter type for the setOnClickListener()
method. It means that you should implement View.OnClickListener
in MainActivity
.
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
You can specify the interpretation order of the axes using the order
parameter:
np.reshape(arr, (2, -1), order='F')
EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.
In previous versions, you can do this:
^(?:(?!filename\.js$).)*\.js$
This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.
^ # Start of string
(?: # Try to match the following:
(?! # First assert that we can't match the following:
filename\.js # filename.js
$ # and end-of-string
) # End of negative lookahead
. # Match any character
)* # Repeat as needed
\.js # Match .js
$ # End of string
Another edit:
It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:
^(?!.*filename\.js$).*\.js$
works just as well:
^ # Start of string
(?! # Assert that we can't match the following:
.* # any string,
filename\.js # followed by filename.js
$ # and end-of-string
) # End of negative lookahead
.* # Match any string
\.js # Match .js
$ # End of string
Boost is a good suggestion. But if you would like to roll your own, it's not so hard.
Basically you just need a way to build up a graph of objects and then output them to some structured storage format (JSON, XML, YAML, whatever). Building up the graph is as simple as utilizing a marking recursive decent object algorithm and then outputting all the marked objects.
I wrote an article describing a rudimentary (but still powerful) serialization system. You may find it interesting: Using SQLite as an On-disk File Format, Part 2.
Well I had the same exact requirement, and Robot class is perfectly fine for me. It works on windows 7 and XP (tried java 6 & 7).
public static void click(int x, int y) throws AWTException{
Robot bot = new Robot();
bot.mouseMove(x, y);
bot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
bot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
May be you could share the name of the program that is rejecting your click?
Inside your function for the click action use
$( "#tabs" ).tabs({ active: # });
Where # is replaced by the tab index you want to select.
Edit: change from selected to active, selected is deprecated
You should probably clarify which logger are you using.
org.apache.commons.logging.Log
interface has method void error(Object message, Throwable t)
(and method void info(Object message, Throwable t)
), which logs the stack trace together with your custom message. Log4J implementation has this method too.
So, probably you need to write:
logger.error("BOOM!", e);
If you need to log it with INFO level (though, it might be a strange use case), then:
logger.info("Just a stack trace, nothing to worry about", e);
Hope it helps.
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
I learned Vim. It wasn't too much effort. Now I absolutely love ci" ci( cw V:s/from/to/g
If you want to find nth Salary from a table (here n should be any thing like 1st or 2nd or 15th highest Salaries)
This is the Query for to find nth Salary:
SELECT DISTINCT Salary FROM tblemployee ORDER BY Salary DESC LIMIT 1 OFFSET (n-1)
If you want to find 8th highest salary, query should be :
SELECT DISTINCT Salary FROM tblemployee ORDER BY Salary DESC LIMIT 1 OFFSET 7
Note: OFFSET starts from 0th position, and hence use N-1 rule here
There is a pure JavaSript way that is not depended on any stacks:
const blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};
For using this helper function you should set a callback, example:
blobToBase64(blobData).then(res => {
// do what you wanna do
console.log(res); // res is base64 now
});
I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:
fetch(imageAddressAsStringValue)
.then(res => res.blob())
.then(blobToBase64)
.then(finalResult => {
storeOnMyLocalDatabase(finalResult);
});
memset(msg, 0, 65546)
It's possible that the error didn't occur in the dot product, but after. For example try this
a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c
np.dot(a,b) will be fine; however np.dot(a, b) * c is clearly wrong (12x1 X 1x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give you
ValueError: operands could not be broadcast together with shapes (12,1) (1,5)
The error is misleading; however there is an issue on that line.
Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.
Lets take example from java docs to get know how we can declare anonymous functions, classes
The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
englishGreeting.greet();
frenchGreeting.greetSomeone("Fred");
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
Syntax of Anonymous Classes
Consider the instantiation of the frenchGreeting object:
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
The anonymous class expression consists of the following:
new
operatorThe name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
Sorry to jump on this question late in the game but I have an answer for irregular (non-rectangular) shapes. I solved it using SVGs to generate masks of where I want to have the event attached.
The idea is to attach events to inlined SVGs, super cheap and even user friendly because there are plenty of programs for generating SVGs. The SVG can have a layer of the image as a background.
http://jcrogel.com/code/2015/03/18/mapping-images-using-javascript-events/
The draft CSS Selectors Level 4 proposes to add an of <other-selector>
grammar within the :nth-child
selector. This would allow you to pick out the nth child matching a given other selector:
:nth-child(1 of p.myclass)
Previous drafts used a new pseudo-class, :nth-match()
, so you may see that syntax in some discussions of the feature:
:nth-match(1 of p.myclass)
This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.
var span = TimeSpan.FromMinutes(2);
var t = Task.Factory.StartNew(async delegate / () =>
{
this.SomeAsync();
await Task.Delay(span, source.Token);
}, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
source.Cancel(true/or not);
// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)
if u like use some loop thread inside ...
public async void RunForestRun(CancellationToken token)
{
var t = await Task.Factory.StartNew(async delegate
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1), token)
.ContinueWith(task => { Console.WriteLine("End delay"); });
this.PrintConsole(1);
}
}, token) // drop thread options to default values;
}
// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.
$ch = curl_init();
$data = array(
'client_id' => 'xx',
'client_secret' => 'xx',
'redirect_uri' => $x,
'grant_type' => 'xxx',
'code' => $xx,
);
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
It sounds less like a Java synchronization issue and more like a database locking problem.
I don't know if adding a version to all your persistent classes will sort it out, but that's one way that Hibernate can provide exclusive access to rows in a table.
Could be that isolation level needs to be higher. If you allow "dirty reads", maybe you need to bump up to serializable.
Add to pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
Both of the previous answers from Matt York and Cyberbolt are right.
Basic idea is here that you want to get some kind of File explorer in Sublime.
Approach:
1) With File -> New Folder -> Click on Desired folder and Hit Open
you will get new popup window in sublime which for me is very annoying
2) I use second option which is drag'n'drop from nautilus (a.k.a. Files) window. Simply drag'n'drop your file you want to explore from nautilus to sublime sidebar
. That way you stay in the same window and everything is cool.
Don't forget to enable View -> Sidebar -> Show Sidebar and drag'n'drop there from nautilus and of course run it with root privleges
. It works like charm
I like to solve the lack of by reference in JavaScript like this example shows.
The essence of this is that you don't try to create a by reference. You instead use the return functionality and make it able to return multiple values. So there isn't any need to insert your values in arrays or objects.
var x = "First";
var y = "Second";
var z = "Third";
log('Before call:',x,y,z);
with (myFunc(x, y, z)) {x = a; y = b; z = c;} // <-- Way to call it
log('After call :',x,y,z);
function myFunc(a, b, c) {
a = "Changed first parameter";
b = "Changed second parameter";
c = "Changed third parameter";
return {a:a, b:b, c:c}; // <-- Return multiple values
}
function log(txt,p1,p2,p3) {
document.getElementById('msg').innerHTML += txt + '<br>' + p1 + '<br>' + p2 + '<br>' + p3 + '<br><br>'
}
_x000D_
<div id='msg'></div>
_x000D_
You need to use <!DOCTYPE html>
for :hover to work with anything other than the <a>
tag. Try adding that to the top of your HTML.
Just assign the import to a data property
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
then loop through the myJson
property in your template using v-for
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
NOTE
If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.
Vue converts all the properties in the data
option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.
So you can create a custom option as follows:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
then loop through the custom option in your template using $options
:
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
I am missing the awk
solution:
awk 'NF' file
Which would return:
xxxxxx
yyyyyy
zzzzzz
How does this work? Since NF
stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk
perform its default action: print the current line.
Try this
var store = dtpDateTimePicker.Value.Date;
store can be anything entity object etc.
In order to rename a table in a different schema, try:
ALTER TABLE owner.mytable RENAME TO othertable;
The rename command (as in "rename mytable to othertable
") only supports renaming a table in the same schema.
First, give permission for execution:-
chmod +x script_name
sh script_name
bash script_name
./script_name
NOTE:-you can check if the file is executable or not by using 'ls -a'
Just wanted to add extension method for an array.
interface Array<T> {
remove(element: T): Array<T>;
}
Array.prototype.remove = function (element) {
const index = this.indexOf(element, 0);
if (index > -1) {
return this.splice(index, 1);
}
return this;
};
Scandit is a startup whose goal is to replace bulky, expensive laser barcode scanners with cheap mobile phones.
There are SDKs for Android, iOS, Windows, C API/Linux, React Native, Cordova/PhoneGap, Xamarin.
There is also Scandit Barcode Scanner SDK for the Web which the WebAssembly version of the SDK. It runs in modern browsers, also on phones.
There's a client library that also provides a barcode picker component. It can be used like this:
<div id="barcode-picker" style="max-width: 1280px; max-height: 80%;"></div>
<script src="https://unpkg.com/scandit-sdk"></script>
<script>
console.log('Loading...');
ScanditSDK.configure("xxx", {
engineLocation: "https://unpkg.com/scandit-sdk/build/"
}).then(() => {
console.log('Loaded');
ScanditSDK.BarcodePicker.create(document.getElementById('barcode-picker'), {
playSoundOnScan: true,
vibrateOnScan: true
}).then(function(barcodePicker) {
console.log("Ready");
barcodePicker.applyScanSettings(new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39", "code93", "itf", "qr"],
codeDuplicateFilter: 1000
}));
barcodePicker.onScan(function(barcodes) {
console.log(barcodes);
});
});
});
</script>
Disclaimer: I work for Scandit
TLDR;
use location.href
or better use window.location.href
;
However if you read this you will gain undeniable proof.
The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.
location = "#/mypath/otherside"
var sections = location.split('/')
This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?
it has location
instead of location.href
what about this
var mystring = location = "#/some/spa/route"
what is the value of mystring
? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location
is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?
This i can pretty much guess all browsers will handle the same.
var mystring = location.href = "#/some/spa/route"
What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?
This conversation is so much deeper than just the location
object however. What this conversion is about what kind of programmer you want to be?
If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.
There will be more objects. There will be new syntax.
You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.
var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"
With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.
Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.
Do the things that you can consistently do.
+"2"
<-- this right here parses the string to a number. should you use it?
or should you use parseInt("2")
?
what about var num =+"2"
?
From what you have learn, from the minds of stackoverflow i am not too hopefully.
If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.
Let me show you how this pays off.
Normally I place ;
on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.
I wrote something similar to this in es6 and babel
var a = "hello world"
(async function(){
//do work
})()
This code fail and took forever to figure out. For some reason what it saw was
var a = "hello world"(async function(){})()
hidden deep within the source code it was telling me "hello world" is not a function.
For more fun node doesn't show the source maps of transpiled code.
Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.
I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.
Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.
what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.
My last note to ponder upon.
Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.
You can use more things plugins, Libraries with out fear of interruption between the codes.
for the record. use
window.location.href
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s.substring(2);
}
Here and easy Example.
<!-- Navigation bar-->
<nav class="navbar navbar-toggleable-md bg-info navbar-inverse">
<div class="container">
<button class="navbar-toggler" data-toggle="collapse" data-target="#mainMenu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainMenu">
<div class="navbar-nav ml-auto " style="width:100%">
<a class="nav-item nav-link active" href="#">Home</a>
<a class="nav-item nav-link" href="#">About</a>
<a class="nav-item nav-link" href="#">Training</a>
<a class="nav-item nav-link" href="#">Contact</a>
</div>
</div>
</div>
</nav>
If you have Python 2.6 or newer, use format
:
'{0:.3g}'.format(num)
For Python 2.5 or older:
'%.3g'%(num)
Explanation:
{0}
tells format
to print the first argument -- in this case, num
.
Everything after the colon (:) specifies the format_spec
.
.3
sets the precision to 3.
g
removes insignificant zeros. See
http://en.wikipedia.org/wiki/Printf#fprintf
For example:
tests=[(1.00, '1'),
(1.2, '1.2'),
(1.23, '1.23'),
(1.234, '1.23'),
(1.2345, '1.23')]
for num, answer in tests:
result = '{0:.3g}'.format(num)
if result != answer:
print('Error: {0} --> {1} != {2}'.format(num, result, answer))
exit()
else:
print('{0} --> {1}'.format(num,result))
yields
1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
Using Python 3.6 or newer, you could use f-strings
:
In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'
Suppose you have this file:
something
name
comment
phone
email
something else
and more ...
You want to add "vendor_" in front of "name", "comment", "phone", and "email", regardless of where they appear in the file.
:%s/\<\(name\|comment\|phone\|email\)\>/vendor_\1/gc
The c
flag will prompt you for confirmation. You can drop that if you don't want the prompt.
When I have a similar issue when reading text files i use...
f = open('file','rt', errors='ignore')
All four answers so far are incorrect, in that they assert a specific order of events.
Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.
So.
For the built-in C++ prefix operator,
++x
increments x
and produces (as the expression's result) x
as an lvalue, while
x++
increments x
and produces (as the expression's result) the original value of x
.
In particular, for x++
there is no no time ordering implied for the increment and production of original value of x
. The compiler is free to emit machine code that produces the original value of x
, e.g. it might be present in some register, and that delays the increment until the end of the expression (next sequence point).
Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.
By using docker-compose
:
Assuming that you have following directory layout:
$MYAPP_ROOT/docker-compose.yml
/Docker/init.sql
/Docker/db.Dockerfile
File: docker-compose.yml
version: "3.3"
services:
db:
build:
context: ./Docker
dockerfile: db.Dockerfile
volumes:
- ./var/pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
File: Docker/init.sql
CREATE USER myUser;
CREATE DATABASE myApp_dev;
GRANT ALL PRIVILEGES ON DATABASE myApp_dev TO myUser;
CREATE DATABASE myApp_test;
GRANT ALL PRIVILEGES ON DATABASE myApp_test TO myUser;
File: Docker/db.Dockerfile
FROM postgres:11.5-alpine
COPY init.sql /docker-entrypoint-initdb.d/
Composing and starting services:
docker-compose -f docker-compose.yml up --no-start
docker-compose -f docker-compose.yml start
Also you can use guppy module.
>>> from guppy import hpy; hp=hpy()
>>> hp.heap()
Partition of a set of 25853 objects. Total size = 3320992 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 11731 45 929072 28 929072 28 str
1 5832 23 469760 14 1398832 42 tuple
2 324 1 277728 8 1676560 50 dict (no owner)
3 70 0 216976 7 1893536 57 dict of module
4 199 1 210856 6 2104392 63 dict of type
5 1627 6 208256 6 2312648 70 types.CodeType
6 1592 6 191040 6 2503688 75 function
7 199 1 177008 5 2680696 81 type
8 124 0 135328 4 2816024 85 dict of class
9 1045 4 83600 3 2899624 87 __builtin__.wrapper_descriptor
<90 more rows. Type e.g. '_.more' to view.>
And:
>>> hp.iso(1, [1], "1", (1,), {1:1}, None)
Partition of a set of 6 objects. Total size = 560 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 17 280 50 280 50 dict (no owner)
1 1 17 136 24 416 74 list
2 1 17 64 11 480 86 tuple
3 1 17 40 7 520 93 str
4 1 17 24 4 544 97 int
5 1 17 16 3 560 100 types.NoneType
Had to do it... The action script way
//just make sure you pass a number to the function because it would accept you mother in law...
public var rad = function(x:*) {return x*Math.PI/180;}
protected function distHaversine(p1:Object, p2:Object):Number {
var R:int = 6371; // earth's mean radius in km
var dLat:Number = rad(p2.lat() - p1.lat());
var dLong:Number = rad(p2.lng() - p1.lng());
var a:Number = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c:Number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d:Number = R * c;
return d;
}
Assuming a simple table:
CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);
We can capture IDENTITY
values in a table variable for further consumption.
DECLARE @IDs TABLE(ID INT);
-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name)
OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';
SELECT ID FROM @IDs;
The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY()
only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.
You cannot do it with pure CSS - the CSS3 spec even has a specific quote about this:
Note: There is no control over the spacing of the dots and dashes, nor over the length of the dashes. Implementations are encouraged to choose a spacing that makes the corners symmetrical.
You can, however, use either a border-image or a background image that does the trick.
Just made this piece of code, wich converts "this.altura" from negative to positive number. Hope this helps someone in need
if(this.altura < 0){
String aux = Integer.toString(this.altura);
char aux2[] = aux.toCharArray();
aux = "";
for(int con = 1; con < aux2.length; con++){
aux += aux2[con];
}
this.altura = Integer.parseInt(aux);
System.out.println("New Value: " + this.altura);
}
You can try this:
//Your class instance
Publication publication = new Publication();
//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");
//Get method
Method method = c.getDeclaredMethod ("setTitle", String.class);
//set value
method.invoke (publication, "Value to want to set here...");
rbind.fill
from the package plyr
might be what you are looking for.
jkoreska's solution is perfect if you know the titles before hand, but you may need to set the title based on data you get from a resource etc.
My solution requires a single service. Since the rootScope is the base of all DOM elements, we don't need to put a controller on the html element like someone mentioned
app.service('Page', function($rootScope){
return {
setTitle: function(title){
$rootScope.title = title;
}
}
});
doctype html
html(ng-app='app')
head
title(ng-bind='title')
// ...
app.controller('SomeController', function(Page){
Page.setTitle("Some Title");
});
I was getting these errors too and was stumped. After reading and trying the two answers above, I was still getting the error.
However,I checked the processes tab of Task Manager to find a rogue copy of 'eclipse.exe *32' that the UI didn' t show as running. I guess this should have been obvious as the error does suggest that the reason the emulator/phone cannot connect is because it's already established a connection with the second copy.
Long story short, make sure via Task Manager that no other Eclipse instances are running before resorting to a PC restart!
You need to implement your own MessageBodyReader
and MessageBodyWriter
for your class Lorg.shoppingsite.model.entity.jpa.User
.
package javax.ws.rs.ext;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface MessageBodyReader<T extends Object> {
public boolean isReadable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public T readFrom(Class<T> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException;
}
package javax.ws.rs.ext;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface MessageBodyWriter<T extends Object> {
public boolean isWriteable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public long getSize(T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public void writeTo(T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException;
}
I did change OS on my server quite a few times trying to get the most comfortable system.
It used to work very well most of the time but lastly I got this 502 Gateway error.
I use a php fpm socket for each account instead of keeping the same one for all. So if one crashes, at least the other applications keep running.
I used to have user and group www-data. But this changed on my Debian 8 with latest Nginx 1.8 and php5-fpm.
The default user is nginx and so is the group. To be sure of this, the best way is to check the /etc/group and /etc/passwd files. These can't lie.
It is there I found that now I have nginx in both and no longer www-data.
Maybe this can help some people still trying to find out why the error message keeps coming up.
It worked for me.
git add
adds your modified files to the queue to be committed later. Files are not committed
git commit
commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a
git push
pushes your changes to the remote repository.
This figure from this git cheat sheet gives a good idea of the work flow
git add
isn't on the figure because the suggested way to commit is the combined git commit -a
, but you can mentally add a git add
to the change block to understand the flow.
Lastly, the reason why push
is a separate command is because of git
's philosophy. git
is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push
is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.
With the newest API, here's the code I used for it
/*params*/
NSDictionary *params = @{
@"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
@"fields": @"id"
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"me"
parameters:params
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSDictionary *res = result;
//res is a dict that has the key
NSLog([res objectForKey:@"id"]);
I personally use import because, we can import the required methods, members by using import.
import {foo, bar} from "dep";
FileName: dep.js
export foo function(){};
export const bar = 22
Credit goes to Paul Shan. More info.
You guys are complicating things. You can simple do this from CSS.
#carousel li { background-position:0px 0px; }
#carousel li:hover { background-position:100px 0px; }
Assuming that you are using a spfile to start the database
alter system set open_cursors = 1000 scope=both;
If you are using a pfile instead, you can change the setting for the running instance
alter system set open_cursors = 1000
You would also then need to edit the parameter file to specify the new open_cursors
setting. It would generally be a good idea to restart the database shortly thereafter to make sure that the parameter file change works as expected (it's highly annoying to discover months later the next time that you reboot the database that some parameter file change than no one remembers wasn't done correctly).
I'm also hoping that you are certain that you actually need more than 300 open cursors per session. A large fraction of the time, people that are adjusting this setting actually have a cursor leak and they are simply trying to paper over the bug rather than addressing the root cause.
Your formula is wrong. You probably meant something like:
=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Another equivalent:
=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Or even shorter:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))
OR EVEN SHORTER:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
If your object is the same object of the ones you are using within the array, you should be able to get the index of the Object in the same way you do as if it was a string.
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var qazCLONE = { // new object instance and same structure
hello: 'stevie',
foo: 'baz'
}
var myArray = [hello,qaz];
myArray.indexOf(qaz) // should return 1
myArray.indexOf(qazCLONE) // should return -1
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
Changing these values worked for me. I found it by looking at the Developer Tools of Chrome
.btn-primary:not(:disabled):not(.disabled).active,
.btn-primary:not(:disabled):not(.disabled):active,
.show>.btn-primary.dropdown-toggle {
color: #fff;
background-color: /*Change This*/;
border-color: /*Change This*/;
}
This retains the shadow of the button too, it only changes the color of the button on-click.
You should add following lines while creating a project. It will always ignore .DS_Store
to be pushed to the repository.
*.DS_Store
this will ignore .DS_Store while code commit.
git rm --cached .DS_Store
this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.
## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store
I think this will happen if you'll use 'async defer' for (the file that contains the filter) while working with angularjs:
<script src="js/filter.js" type="text/javascript" async defer></script>
if you do, just remove 'async defer'.
You can run a single test class, but not a single method within a test class. You use the simple name of the class not the fully-qualified name of the class. So, if you have a test in "org.sonatype.test.MyTest" and that is the only test you want to run, your command line would look like this:
mvn test -Dtest=MyTest
For me, my server was using Python 2.4. I simply looked up Python 2.7, which was installed on my server, and created an alias.
alias python=python2.7
If you need to know more, I found the solution here
I had the same problem with Eclipse v3.7 (Indigo) and m2eclipse as my Maven plugin. The error was easily solved by explicitly stating the execution phase within the plugin definition. So my pom looks like this:
<project>
...
<build>
...
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.0</version>
<configuration>
<timestampFormat>yyyy-MM-dd_HH-mm-ss</timestampFormat>
</configuration>
<executions>
<execution>
*<phase>post-clean</phase>*
<goals>
<goal>create-timestamp</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
...
$mystring = "this is the text I would like to truncate";
// Pass your variable to the function
$mystring = truncate($mystring);
// Truncated tring printed out;
echo $mystring;
//truncate text function
public function truncate($text) {
//specify number fo characters to shorten by
$chars = 25;
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}
exit(X)
, where X is a number (according to the doc) should work.
But it is not recommended by Apple and won't be accepted by the AppStore.
Why? Because of these guidelines (one of my app got rejected):
We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.
Please refer to the attached screenshot/s for reference.
The iOS Human Interface Guidelines specify,
"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:
Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.
Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."
> It would be appropriate to remove any mechanisms for quitting your app.
Plus, if you try to hide that function, it would be understood by the user as a crash.
You could try jQuery UI's .position method.
$("#mydiv").position({
of: $('#mydiv').parent(),
my: 'left+200 top+200',
at: 'left top'
});
Now i use this method based in Duncan Babbage response:
+ (UIImageView *) tintImageView: (UIImageView *)imageView withColor: (UIColor*) color{
imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[imageView setTintColor:color];
return imageView;
}
The following ways work.
// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));
// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
StartupB(port, path);
});
t2.Start();
// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();
The Startup methods have following signature for these examples.
public void StartupA(object parameters);
public void StartupB(int port, string path);
SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;
In the new desktop versions, you can add hyperlink by pressing ctrl + k and typing links.
We can increase maximum upload file size for WordPress media uploads in 3 different ways.
That's are
For .htaccess way, add following code,
php_value upload_max_filesize 1024M
php_value post_max_size 1024M
php_value max_execution_time 1000
php_value max_input_time 1000
for PHP.INI file method, add following code,
upload_max_filesize = 1024M
post_max_size = 1024M
max_execution_time = 1000
for Theme’s Functions.php File, add following code,
@ini_set( ‘upload_max_size’ , ’1024M’ );
@ini_set( ‘post_max_size’, ’1024M’);
@ini_set( ‘max_execution_time’, ’1000' );
This uses the above ideas but makes it a derived 'more sensitive' collection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections;
namespace somethingelse
{
public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
// this collection also reacts to changes in its components' properties
public ObservableCollectionEx() : base()
{
this.CollectionChanged +=new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ObservableCollectionEx_CollectionChanged);
}
void ObservableCollectionEx_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach(T item in e.OldItems)
{
//Removed items
item.PropertyChanged -= EntityViewModelPropertyChanged;
}
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach(T item in e.NewItems)
{
//Added items
item.PropertyChanged += EntityViewModelPropertyChanged;
}
}
}
public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
//This will get called when the property of an object inside the collection changes - note you must make it a 'reset' - I don't know, why
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(args);
}
}
}
for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!
i mean instead of this junk ternary condition inside your jsx in render part of your component:
// some component body
return(
<section>
{/* some ui */}
{ someCondition && <MyComponent /> }
or
{ someCondition ? <MyComponent /> : null }
{/* more ui */}
</section>
)
you can check than condition inside your component like:
const MyComponent:React.FC = () => {
// get someCondition from context at here before any thing
if(someCondition) return null; // i mean this part , checking inside component!
return (
<section>
// some ui...
</section>
)
}
Just Consider that in my case i provide the someCondition
variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition
inside MyComponent
.
Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:
// some component body
return(
<section>
{/* some ui */}
<MyComponent />
{/* more ui */}
</section>
)
and MyComponent
would handle the rest for you!
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
If you want to get the second to last word in a text, you can use this macro as a function in your spreadsheet:
Public Function Get2ndText(S As String) As String
Dim sArr() As String
Dim i As Integer
sArr = Split(S, " ")
'get the next to the last string
i = UBound(sArr) - 1
Get2ndText = sArr(i)
End Function
Then in your spreadsheet B1 as the text:
CURRENT OWNER 915 BROADWAY ST HOUSTON TX 77012-2126
in B2 your formula would be:
=Get2ndText(B1)
The result would be
TX
Follow the following steps:
Use the LastLogonDate property and you won't have to convert the date/time. lastLogonTimestamp should equal to LastLogonDate when converted. This way, you will get the last logon date and time across the domain without needing to convert the result.
Full validation example with javascript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Radio button: full validation example with javascript</title>
<script>
function send() {
var genders = document.getElementsByName("gender");
if (genders[0].checked == true) {
alert("Your gender is male");
} else if (genders[1].checked == true) {
alert("Your gender is female");
} else {
// no checked
var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
document.getElementById('msg').innerHTML = msg;
return false;
}
return true;
}
function reset_msg() {
document.getElementById('msg').innerHTML = '';
}
</script>
</head>
<body>
<form action="" method="POST">
<label>Gender:</label>
<br />
<input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
<br />
<input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
<br />
<div id="msg"></div>
<input type="submit" value="send>>" onclick="return send();" />
</form>
</body>
</html>
Regards,
Fernando
For people developing with Android studio:
if you install adb with the command line it will probably conflict with the adb version installed by Flutter.
You can check that you have this problem with 2 different versions easily:
find /home -iname "*adb"|grep -i android
And then compare the return value between adb version
(located at usr/bin/adb and most likely a symbolic link for /usr/lib/android-sdk/platform-tools/adb ) with ~/Android/Sdk/platform-tools/adb version
You will get this kind of output:
$ ~/Android/Sdk/platform-tools/adb version
Android Debug Bridge version 1.0.41
Version 30.0.5-6877874
Installed as /home/{{{user}}/Android/Sdk/platform-tools/adb
$ adb version
Android Debug Bridge version 1.0.39
Version 1:8.1.0+r23-5~18.04
Installed as /usr/lib/android-sdk/platform-tools/adb
My advice is hence the following: DO NOT RELY ON sudo apt-get install adb
1/ You first want to remove adb installed through the command line: (this is way cleaner than sudo rm usr/bin/adb
sudo apt-get remove adb
2/ Then create symbolic link from the sdk to usr/bin (top answer already provided):
sudo ln -s ~/Android/Sdk/platform-tools/adb /usr/bin/adb
Now you can use the different command lines adb devices
, adb start-server
, adb kill-server
Some of the other solutions might not work if you created the cookie manually.
Here's a quick way to delete a cookie:
document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;
you could always create a new list which is a result of adding two lists.
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
Using the attribute method is, in fact, easier and more straightforward.
Using Ruby with the Selenium and PageObject gems, to get the class associated with a certain element, the line would be element.attribute(Class)
.
The same concept applies if you wanted to get other attributes tied to the element. For example, if I wanted the string of an element, element.attribute(String)
.
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main
are:
int argc
- the number of arguments passed into your program when it was run. It is at least 1
.char **argv
- this is a pointer-to-char *
. It can alternatively be this: char *argv[]
, which means 'array of char *
'. This is an array of C-style-string pointers.For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c
. It'll compile and build a default a.out
executable.
[birryree@lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv
, argv[0]
is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1]
and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
And you could check if argv[1]
was integral
, maybe like strcmp("integral", argv[1]) == 0
.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt
.
Doing alist = []
does not clear the list, just creates an empty list and binds it to the variable alist
. The old list will still exist if it had other variable bindings.
To actually clear a list in-place, you can use any of these ways:
alist.clear() # Python 3.3+, most obvious
del alist[:]
alist[:] = []
alist *= 0 # fastest
See the Mutable Sequence Types documentation page for more details.
From my answer here, thought this might be useful:
I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:
Step 1: Identify the Database Version
$ mysql --version
You'll see some output like this with MySQL:
$ mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
mysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.
Step 2: Stopping the Database Server
To change the root password, you have to shut down the database server beforehand.
You can do that for MySQL with:
$ sudo systemctl stop mysql
And for MariaDB with:
$ sudo systemctl stop mariadb
Step 3: Restarting the Database Server Without Permission Checking
If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
$ sudo mysqld_safe --skip-grant-tables --skip-networking &
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now you can connect to the database as the root user, which should not ask for a password.
$ mysql -u root
You'll immediately see a database shell prompt instead.
MySQL Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
MariaDB Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Now that you have root access, you can change the root password.
Step 4: Changing the Root Password
mysql> FLUSH PRIVILEGES;
Now we can actually change the root password.
For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
Make sure to replace new_password
with your new password of choice.
Note: If the ALTER USER
command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET
to reset the root password instead.
[IMPORTANT] This is the specific line that fixed my particular issue:
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
Query OK, 0 rows affected (0.00 sec)
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
Step 5: Restart the Database Server Normally
The tutorial goes into some further steps to restart the database, but the only piece I used was this:
For MySQL, use: $ sudo systemctl start mysql
For MariaDB, use:
$ sudo systemctl start mariadb
Now you can confirm that the new password has been applied correctly by running:
$ mysql -u root -p
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
Conclusion
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
@jim's answer is correct -- fuser
is what you want.
Additionally (or alternately), you can use lsof
to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser
can do that with its -k
option. You can have fuser
use other signals with the -s
option -- check the man page for details.)
For example, with a tail -F /etc/passwd
running in one window:
ghoti@pc:~$ lsof | grep passwd
tail 12470 ghoti 3r REG 251,0 2037 51515911 /etc/passwd
Note that you can also use lsof
to find out what processes are using particular sockets. An excellent tool to have in your arsenal.
All C++ compilers have one serious performance problem to deal with. Compiling C++ code is a long, slow process.
Compiling headers included on top of C++ files is a very long, slow process. Compiling the huge header structures that form part of Windows API and other large API libraries is a very, very long, slow process. To have to do it over, and over, and over for every single Cpp source file is a death knell.
This is not unique to Windows but an old problem faced by all compilers that have to compile against a large API like Windows.
The Microsoft compiler can ameliorate this problem with a simple trick called precompiled headers. The trick is pretty slick: although every CPP file can potentially and legally give a sligthly different meaning to the chain of header files included on top of each Cpp file (by things like having different macros #define'd in advance of the includes, or by including the headers in different order), that is most often not the case. Most of the time, we have dozens or hundreds of included files, but they all are intended to have the same meaning for all the Cpp files being compiled in your application.
The compiler can make huge time savings if it doesn't have to start to compile every Cpp file plus its dozens of includes literally from scratch every time.
The trick consists of designating a special header file as the starting point of all compilation chains, the so called 'precompiled header' file, which is commonly a file named stdafx.h simply for historical reasons.
Simply list all your big huge headers for your APIs in your stdafx.h file, in the appropriate order, and then start each of your CPP files at the very top with an #include "stdafx.h"
, before any meaningful content (just about the only thing allowed before is comments).
Under those conditions, instead of starting from scratch, the compiler starts compiling from the already saved results of compiling everything in stdafx.h
.
I don't believe that this trick is unique to Microsoft compilers, nor do I think it was an original development.
For Microsoft compilers, the setting that controls the use of precompiled headers is controlled by a command line argument to the compiler: /Yu "stdafx.h"
. As you can imagine, the use of the stdafx.h
file name is simply a convention; you can change the name if you so wish.
In Visual Studio 2010, this setting is controlled from the GUI via Right-clicking on a CPP Project, selecting 'Properties' and navigating to "Configuration Properties\C/C++\Precompiled Headers". For other versions of Visual Studio, the location in the GUI will be different.
Note that if you disable precompiled headers (or run your project through a tool that doesn't support them), it doesn't make your program illegal; it simply means that your tool will compile everything from scratch every time.
If you are creating a library with no Windows dependencies, you can easily comment out or remove #include
s from the stdafx.h
file. There is no need to remove the file per se, but clearly you may do so as well, by disabling the precompile header setting above.
I tried both
npm rebuild node-sass
and
npm install --save node-sass
Later by seeing EACCESS, i checked the folder permission of /node_modules, which was not 777 permission
Then I gave
chmod -R 777 *
-R for recursively(setting the same permission not in the dir but also inside nested sub dir) * is for all files in current directory
What is file permission
To check for permission you can use
ls -l
If u don't know about it, first see here, then check the url
Every file and directory has permission of 'rwx'(read, write, execute). and if 'x' permission is not there, then you can not execture, if no 'w', you can not write into the file. if some thing is missiing it will show in place of r/w/x with '-'. So, if 'x' permission is not there, it will show like 'rw-'
And there will be 3 category of user Owner(who created the file/directory), Group(some people who shares same permission and user previlege), Others(general public)
So 1st letter is 'd'(if it is a directory) or '-'(if it is not a directory), followed by rwx for owner, followed by for group, followed by other
drwxrwxrwx
For example, for 'node_modules'directory I want to give permission to owner all permission and for rest only read, then it will be
drwxr--r--
And about the number assume for 'r/w/x' it is 1 and for '-' it is 0, 777, first 7 is for owner, followed by group, followed by other
Let's assume the permission is rwxr-xrw-
Now 'rwx' is like '111' and it's equivalent decimal is 1*2^2+1*2^1+1*2^0=7
Now 'r-x' is like '101' and it's equivalent decimal is 1*2^2+0*2^1+1*2^0=5
Now 'rw-' is like '110' and it's equivalent decimal is 1*2^2+1*2^1+0*2^0=6
So, it will be 756
According to Pure CSS Scrollable Table with Fixed Header , I wrote a DEMO to easily fix the header by setting overflow:auto
to the tbody.
table thead tr{
display:block;
}
table th,table td{
width:100px;//fixed width
}
table tbody{
display:block;
height:200px;
overflow:auto;//set tbody to auto
}
Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.
strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]
The answer for this will be ["first", "second"]
.
If you want to use filter
method instead, you can do like
list(filter(lambda item: item.strip(), strings))
. This is give the same result.
In C++, nested classes are not connected to any instance of the outer class. If you want bar
to access non-static members of foo
, then bar
needs to have access to an instance of foo
. Maybe something like:
class bar {
public:
int getA(foo & f ) {return foo.a;}
};
Or maybe
class bar {
private:
foo & f;
public:
bar(foo & g)
: f(g)
{
}
int getA() { return f.a; }
};
In any case, you need to explicitly make sure you have access to an instance of foo
.
For me, I ran into this issue after switching over from bash to zsh so I could get my console to look all awesome fantastic-ish with Hyper and the snazzy theme. I was trying to run my react-native application using react-native run-android
and running into the op's issue. Adding the following into my ~.zshrc
file solved the issue for me:
export ANDROID_HOME=~/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow
and pagehide
events:
window.addEventListener("pageshow", () => {
// update hidden input field
});
.class
is used when there isn't an instance of the class available.
.getClass()
is used when there is an instance of the class available.
object.getClass()
returns the class of the given object.
For example:
String string = "hello";
System.out.println(string.getClass().toString());
This will output:
class java.lang.String
This is the class of the string object :)
Digest Authentication communicates credentials in an encrypted form by applying a hash function to: the username, the password, a server supplied nonce value, the HTTP method and the requested URI.
Whereas Basic Authentication uses non-encrypted base64 encoding.
Therefore, Basic Authentication should generally only be used where transport layer security is provided such as https.
See RFC-2617 for all the gory details.
All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of &
which is not followed by #
(e.g.  
,  
, etc), the XML parser is implicitly looking for one of the five predefined entity names lt
, gt
, amp
, quot
and apos
, or any manually defined entity name. However, in your particular case, you was using &
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The entity name must immediately follow the '&' in the entity reference
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The &
must be escaped as &
.
So, in your particular case, the
if (Modernizr.canvas && Modernizr.localstorage &&
must become
if (Modernizr.canvas && Modernizr.localstorage &&
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="onload.js" target="body" />
(note the target="body"
; this way JSF will automatically render the <script>
at the very end of <body>
, regardless of where <h:outputScript>
itself is located, hereby achieving the same effect as with window.onload
and $(document).ready()
; so you don't need to use those anymore in that script)
This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.
Query all users and filter by the list from your text file:
$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users -contains $_.SamAccountName } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
Get-ADUser -Filter '*'
returns all AD user accounts. This stream of user objects is then piped into a Where-Object
filter, which checks for each object if its SamAccountName
property is contained in the user list from your input file ($Users
). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.
You can further optimize the code by replacing the -contains
operator with hashtable lookups:
$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users.ContainsKey($_.SamAccountName) } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
There is another way of enabling this,
use hadoop hdfs -copyFromLocal to copy the .csv data file from your local computer to somewhere in HDFS, say '/path/filename'
enter Hive console, run the following script to load from the file to make it as a Hive table. Note that '\054' is the ascii code of 'comma' in octal number, representing fields delimiter.
CREATE EXTERNAL TABLE table name (foo INT, bar STRING)
COMMENT 'from csv file'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\054'
STORED AS TEXTFILE
LOCATION '/path/filename';
You can have multiple exclude options for tar so
$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
etc will work. Make sure to put --exclude
before the source and destination items.
I used the following script to read a text file that has a list of all my SVN repos and convert them to GIT, and later use git clone --bare to convert to a bare git repo
#!/bin/bash
file="list.txt"
while IFS= read -r repo_name
do
printf '%s\n' "$repo_name"
sudo git svn clone --shared --preserve-empty-dirs --authors-file=users.txt file:///programs/svn/$repo_name
sudo git clone --bare /programs/git/$repo_name $repo_name.git
sudo chown -R www-data:www-data $repo_name.git
sudo rm -rf $repo_name
done <"$file"
list.txt has the format
repo1_name
repo2_name
and users.txt has the format
(no author) = Prince Rogers <[email protected]>
www-data is the Apache web server user, permission is needed to push changes over HTTP
You can call User-defined Functions in a stored procedure alternately
this may solve your problem to call stored procedure
For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.
Yes, although it uses the same syntax as a for loop.
for x in ['a', 'b']: print(x)
Check the build action of your view (.cshtml file) It should be set to content. In some cases, I have seen that the build action was set to None (by mistake) and this particular view was not deploy on the target machine even though you see that view present in visual studio project file under valid folder
Here is a more modular and cleaner way to circle crop your bitmap in Glide:
BitmapTransformation
then override transform
method like this : For Glide 4.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {}
}
For Glide 3.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public String getId() {
// Return some id that uniquely identifies your transformation.
return "CircularTransformation";
}
}
Glide.with(yourActivity)
.load(yourUrl)
.asBitmap()
.transform(new CircularTransformation())
.into(yourView);
Hope this helps :)
The problem here is that if there are too many data bars the labels will not show.
To fix this, under the "Chart Axis" properties set the Interval value to "=1". Then all the labels will be shown.
Here's a tip sheet I wrote up once, with the commands I actually use regularly:
<Esc>
gets you out of any mode and back to command modeAll insertion commands are terminated with <Esc>
to return to command mode.
<motion>
changes text in the direction of the motion<motion>
deletes in the direction of the motionname
write file to disk as name
tags
file); ^T return to previous position (arbitrary stack of positions maintained)Vim has some features that make it easy to highlight lines that have been changed from a base version in source control. I have created a small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff
You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
This is not possible if you can't change your code. But I like dependency injection and Mockito supports it:
public class First {
@Resource
Second second;
public First() {
second = new Second();
}
public String doSecond() {
return second.doSecond();
}
}
Your test:
@RunWith(MockitoJUnitRunner.class)
public class YourTest {
@Mock
Second second;
@InjectMocks
First first = new First();
public void testFirst(){
when(second.doSecond()).thenReturn("Stubbed Second");
assertEquals("Stubbed Second", first.doSecond());
}
}
This is very nice and easy.
You can use basic regular expressions on strings to find all special characters or use pattern and matcher classes to search/modify/delete user defined strings. This link has some simple and easy to understand examples for regular expressions: http://www.vogella.de/articles/JavaRegularExpressions/article.html
Here is a solution to getting an array (list) of bytes:
I found that you needed to convert the Int to a byte first, before passing it to the bytes():
bytes(int('0xA2', 16).to_bytes(1, "big"))
Then create a list from the bytes:
list(frame)
So your code should look like:
frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)
The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.
For those who still searching a way to put the length of an array into a variable:
foo=$(echo ${'ARRAY[*]}
The solution I have used is:
<svg>
<line x1="100" y1="100" x2="500" y2="100" style="stroke:black; stroke-width: 2"/>
<text x="150" y="105" style="stroke:white; stroke-width:0.6em">Hello World!</text>
<text x="150" y="105" style="fill:black">Hello World!</text>
</svg>
_x000D_
A duplicate text item is being placed, with stroke and stroke-width attributes. The stroke should match the background colour, and the stroke-width should be just big enough to create a "splodge" on which to write the actual text.
A bit of a hack and there are potential issues, but works for me!
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
It might be easier with vlookup. Try this:
=IFERROR(VLOOKUP(D2,G:H,2,0),"")
The IFERROR()
is for no matches, so that it throws ""
in such cases.
VLOOKUP
's first parameter is the value to 'look for' in the reference table, which is column G and H.
VLOOKUP
will thus look for D2
in column G and return the value in the column index 2
(column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.
The last parameter is 0
(or equivalently FALSE
) to mean an exact match. That's what you need as opposed to approximate match.
In fact return (i++)
will only return 10.
The ++ and -- operators can be placed before or after the variable, with different effects. If they are before, then they will be processed and returned and essentially treated just like (i-1) or (i+1), but if you place the ++ or -- after the i, then the return is essentailly
return i;
i + 1;
So it will return 10 and never increment it.
<script src="foo.js?<?php echo date('YmdHis',filemtime('foo.js'));?>"></script>
It will refresh if modify.
As of Python 3.6, you can use the following (similar to @slashCoder):
def to_raw(string):
return fr"{string}"
my_dir ="C:\data\projects"
to_raw(my_dir)
yields 'C:\\data\\projects'
. I'm using it on a Windows 10 machine to pass directories to functions.
I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:
public function exportObj($method = 'a')
{
if($method == 'j')
{
return json_encode(get_object_vars($this));
}
else
{
return get_object_vars($this);
}
}
either way, get_object_vars()
is probably useful to you.
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
A more savvy way to do this is to store your sudo
password in a secure vault such as LastPass or KeePass and then pass it to ansible-playbook
using the -e@
but instead of hardcoding the contents in an actual file, you can use the construct -e@<(...)
to run a command in a sub-shell, and redirect its output (STDOUT) to a anonymous file descriptor, effectively feeding the password to the -e@<(..)
.
$ ansible-playbook -i /tmp/hosts pb.yml \
-e@<(echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)")
The above is doing several things, let's break it down.
ansible-playbook -i /tmp/hosts pb.yml
- obviously running a playbook via ansible-playbook$(lpass show folder1/item1 --password)"
- runs the LastPass CLI lpass
and retrieves the password to useecho "ansible_sudo_pass: ...password..."
- takes the string 'ansible_sudo_pass: ' and combines it with the password supplied by lpass
-e@<(..)
- puts the above together, and connects the subshell of <(...)
as a file descriptor for ansible-playbook
to consume.If you'd rather not type that every time you can simply things like so. First create an alias in your .bashrc
like so:
$ cat ~/.bashrc
alias asp='echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)"'
Now you can run your playbook like this:
$ ansible-playbook -i /tmp/hosts pb.yml -e@<(asp)
When you click on hide me
, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()
You can see this for more clarification
# dump into file
pg_dump myDB > /tmp/myDB.sql
# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'
# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql
# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";'
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'
# see the result
psql myDB -c "SHOW LC_COLLATE"
Version check helped me OpenSSL. OpenSSL_1_0_1f not supported TSLv.1_2 ! Check version and compatibility with TSLv.1_2 on github openssl/openssl . And regenerate your certificate with new openssl
openssl pkcs12 -in path.p12 -out newfile.pem
P.S I don’t know what they were minus, but this solution will really help.
Starting from Angular 9 localization process changed. Check out official doc.
Follow the steps below:
ng add @angular/localize
The Angular repository includes common locales. You can change your app's source locale for the build by setting the source locale in the sourceLocale field of your app's workspace configuration file (angular.json). The build process (described in Merge translations into the app in this guide) uses your app's angular.json file to automatically set the LOCALE_ID token and load the locale data.
so set locale in angular.json
like this (list of available locales can be found here):
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"test-app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"i18n": {
"sourceLocale": "es"
},
....
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
...
"configurations": {
"production": {
...
},
"ru": {
"localize": ["ru"]
},
"es": {
"localize": ["es"]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "test-app:build"
},
"configurations": {
"production": {
"browserTarget": "test-app:build:production"
},
"ru":{
"browserTarget": "test-app:build:ru"
},
"es": {
"browserTarget": "test-app:build:es"
}
}
},
...
}
},
...
"defaultProject": "test-app"
}
Basically you need to define sourceLocale
in i18n
section and add build configuration with specific locale like "localize": ["es"]
. Optionally you can add it so serve
section
build
or serve
: ng serve --configuration=es
In the controller, you need to add the login object as an attribute of the model:
model.addAttribute("login", new Login());
Like this:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String displayLogin(Model model) {
model.addAttribute("login", new Login());
return "login";
}
You should put the print function in your view-details.php file and call it once the file is loaded, by either using
<body onload="window.print()">
or
$(document).ready(function () {
window.print();
});
There are 3 kind of object files.
Contain machine code in a form that can be combined with other relocatable object files at link time, in order to form an executable object file.
If you have an a.c
source file, to create its object file with GCC you should run:
gcc a.c -c
The full process would be: preprocessor (cpp) would run over a.c. Its output (still source) will feed into the compiler (cc1). Its output (assembly) will feed into the assembler (as), which will produce the relocatable object file
. That file contains object code and linking (and debugging if -g
was used) metadata, and is not directly executable.
Special type of relocatable object file that can be loaded dynamically, either at load time, or at run time. Shared libraries are an example of these kinds of objects.
Contain machine code that can be directly loaded into memory (by the loader, e.g execve) and subsequently executed.
The result of running the linker over multiple relocatable object files
is an executable object file
. The linker merges all the input object files from the command line, from left-to-right, by merging all the same-type input sections (e.g. .data
) to the same-type output section. It uses symbol resolution
and relocation
.
When linking against a static library
the functions that are referenced in the input objects are copied to the final executable.
With dynamic libraries
a symbol table is created instead that will enable a dynamic linking with the library's functions/globals. Thus, the result is a partially executable object file, as it depends on the library. If the library doesn't exist, the file can no longer execute).
The linking process can be done as follows:
ld a.o -o myexecutable
The command: gcc a.c -o myexecutable
will invoke all the commands mentioned at point 1 and at point 3 (cpp -> cc1 -> as -> ld1)
1: actually is collect2, which is a wrapper over ld.
The problem is with installing the required Flutter and Dart plugins. There are two ways in which you can achieve this:
Go to Android studio → Settings → plugins → in the search bar search for Flutter and Dart plugins.
If you are installing flutter first, then Dart may get automatically installed along with it, otherwise install them separately.
If you are using VScode, in the activity bar click on extensions or press Ctrl + Shift + X. There you can search for flutter and dart plugins.
Now type flutter doctor.
simply don't close in
remove in.close()
from your code.
If you are using a modern browser, you could use a manifest file to inform the browsers which files need to be updated. This requires no headers, no versions in URLs, etc.
For more details, see: Using the application cache
You are creating three lists, instead of using one (you don't use the return value of DirSearch(d)
). You can use a list as a parameter to save the state:
static void Main(string[] args)
{
var list = new List<string>();
DirSearch(list, ".");
foreach (var file in list)
{
Console.WriteLine(file);
}
}
public static void DirSearch(List<string> files, string startDirectory)
{
try
{
foreach (string file in Directory.GetFiles(startDirectory, "*.*"))
{
string extension = Path.GetExtension(file);
if (extension != null)
{
files.Add(file);
}
}
foreach (string directory in Directory.GetDirectories(startDirectory))
{
DirSearch(files, directory);
}
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
You can use numpy.asarray, for example to convert a list into an array:
>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
I can't comment so here goes. About @David Storey answer.
Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.
transformation: translate(0,10%) rotate(25deg);
The rotate
operation is done first, then the translate
.
See: CSS3 transform order matters: rightmost operation first
On linux you can check epiphany-browser, resizes the windows you'll get same bugs as in ios. Both browsers uses Webkit.
Ubuntu/Mint:
sudo apt install epiphany-browser
I would like to suggest using JOOL library, it hides spliterator magic behind the Seq.seq(iterable)
call and also provides a whole bunch of additional useful functionality.
I created my own functions which work really nicely:
def writeDict(dict, filename, sep):
with open(filename, "a") as f:
for i in dict.keys():
f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")
It will store the keyname first, followed by all values. Note that in this case my dict contains integers so that's why it converts to int
. This is most likely the part you need to change for your situation.
def readDict(filename, sep):
with open(filename, "r") as f:
dict = {}
for line in f:
values = line.split(sep)
dict[values[0]] = {int(x) for x in values[1:len(values)]}
return(dict)
@Redu's solution is a good solution
arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.
if you absolutely don't want to have any looping here's a dirty hack :
Object.defineProperty(Object.prototype, "isActive",{
value: true,
writable: true,
configurable: true,
enumerable: true
});
my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...
Some options:
tr
tr -d '\15\32' < windows.txt > unix.txt
OR
tr -d '\r' < windows.txt > unix.txt
perl
perl -p -e 's/\r$//' < windows.txt > unix.txt
sed
sed 's/^M$//' windows.txt > unix.txt
OR
sed 's/\r$//' windows.txt > unix.txt
To obtain ^M
, you have to type CTRL-V
and then CTRL-M
.
As have been mentioned by others above,Wrap listview with Expanded is the solution.
But when you deal with nested Columns you will also need to limit your ListView to a certain height (faced this problem a lot).
If anyone have another solution please, mention in comment or add answer.
Example
SingleChildScrollView(
child: Column(
children: <Widget>[
Image(image: ),//<< any widgets added
SizedBox(),
Column(
children: <Widget>[
Text('header'), //<< any widgets added
Expanded(child:
ListView.builder(
//here your code
scrollDirection: Axis.horizontal,
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return Container();
}
)
),
Divider(),//<< any widgets added
],
),
],
),
);
You can concatenate the CR and LF:
chr(13)||chr(10)
(on windows)
or just:
chr(10)
(otherwise)
dbms_output.put_line('Hi,'||chr(13)||chr(10) ||'good' || chr(13)||chr(10)|| 'morning' ||chr(13)||chr(10) || 'friends');
Just collected all people's answers:(m new to git plz use it for reference only)
git log
-first check from which commit you want to rebase
git rebase -i HEAD~1
-Here i want to rebase on the second last commit- commit count starts from '1')
-this will open the command line editor (called vim editor i guess)
Then the screen will look something like this:
pick 0c2236d Added new line.
Rebase 2a1cd65..0c2236d onto 2a1cd65 (1 command)
#
Commands:
p, pick = use commit
r, reword = use commit, but edit the commit message
e, edit = use commit, but stop for amending
s, squash = use commit, but meld into previous commit
f, fixup = like "squash", but discard this commit's log message
x, exec = run command (the rest of the line) using shell
d, drop = remove commit
#
These lines can be re-ordered; they are executed from top to bottom.
#
If you remove a line here THAT COMMIT WILL BE LOST.
#
However, if you remove everything, the rebase will be aborted.
#
Note that empty commits are commented out ~ ~
~
~
~
~
~
~
~
~
~
Here change the first line as per your need (using the commands listed above i.e. 'drop' to remove commit etc.) Once done the editing press ':x' to save and exit editor(this is for vim editor only)
And then
git push
If its showing problem then you need to forcefully push the changes to remote(ITS VERY CRITICAL : dont force push if you are working in team)
git push -f origin
It is a very simple and easy way to create an enumerable for your object. The compiler creates a class that wraps your method and that implements, in this case, IEnumerable<object>. Without the yield keyword, you'd have to create an object that implements IEnumerable<object>.
FWIW, the equivalent package for RHEL/Fedora/CentOS/etc and SuSE/OpenSuSE appears to be called 'rubygems'.