I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
Since you want to know how it works, I'll explain it step-by-step.
First you want to bind a function as the image's click handler:
$('#someImage').click(function () {
// Code to do scrolling happens here
});
That will apply the click handler to an image with id="someImage"
. If you want to do this to all images, replace '#someImage'
with 'img'
.
Now for the actual scrolling code:
Get the image offsets (relative to the document):
var offset = $(this).offset(); // Contains .top and .left
Subtract 20 from top
and left
:
offset.left -= 20;
offset.top -= 20;
Now animate the scroll-top and scroll-left CSS properties of <body>
and <html>
:
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});
The method getContentAsByteArray() of the Spring class ContentCachingRequestWrapper reads the body multiple times, but the methods getInputStream() and getReader() of the same class do not read the body multiple times:
"This class caches the request body by consuming the InputStream. If we read the InputStream in one of the filters, then other subsequent filters in the filter chain can't read it anymore. Because of this limitation, this class is not suitable in all situations."
In my case more general solution that solved this problem was to add following three classes to my Spring boot project (and the required dependencies to the pom file):
CachedBodyHttpServletRequest.java:
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private byte[] cachedBody;
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
InputStream requestInputStream = request.getInputStream();
this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new CachedBodyServletInputStream(this.cachedBody);
}
@Override
public BufferedReader getReader() throws IOException {
// Create a reader from cachedContent
// and return it
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
return new BufferedReader(new InputStreamReader(byteArrayInputStream));
}
}
CachedBodyServletInputStream.java:
public class CachedBodyServletInputStream extends ServletInputStream {
private InputStream cachedBodyInputStream;
public CachedBodyServletInputStream(byte[] cachedBody) {
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
}
@Override
public boolean isFinished() {
try {
return cachedBodyInputStream.available() == 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException();
}
@Override
public int read() throws IOException {
return cachedBodyInputStream.read();
}
}
ContentCachingFilter.java:
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
@WebFilter(filterName = "ContentCachingFilter", urlPatterns = "/*")
public class ContentCachingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
System.out.println("IN ContentCachingFilter ");
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(httpServletRequest);
filterChain.doFilter(cachedBodyHttpServletRequest, httpServletResponse);
}
}
I also added the following dependencies to pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
A tuturial and full source code is located here: https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times
There is a package called eclipse-cdt
in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++
already, you need to install that as well, so all you need is:
sudo apt-get install eclipse eclipse-cdt g++
Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudo
s blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get
and hope for the best.
Why would you bother? Load your CSV into Excel like this:
$csv = Join-Path $env:TEMP "process.csv"
$xls = Join-Path $env:TEMP "process.xlsx"
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true
$wb = $xl.Workbooks.OpenText($csv)
$wb.SaveAs($xls, 51)
You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter
if need be.
Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.
$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true
$wb = $xl.Workbooks.Add()
$ws = $wb.Sheets.Item(1)
$ws.Cells.NumberFormat = "@"
$i = 1
Import-Csv $csv | ForEach-Object {
$j = 1
foreach ($prop in $_.PSObject.Properties) {
if ($i -eq 1) {
$ws.Cells.Item($i, $j++).Value = $prop.Name
} else {
$ws.Cells.Item($i, $j++).Value = $prop.Value
}
}
$i++
}
$wb.SaveAs($xls, 51)
$wb.Close()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
Obviously this second approach won't perform too well, because it's processing each cell individually.
$this->db->get()->row()->campaign_id;
For me it was that I was passing a function result as 2-way binding input '=' to a directive that was creating a new object every time.
so I had something like that:
<my-dir>
<div ng-repeat="entity in entities">
<some-other-dir entity="myDirCtrl.convertToSomeOtherObject(entity)"></some-other-dir>
</div>
</my-dir>
and the controller method on my-dir was
this.convertToSomeOtherObject(entity) {
var obj = new Object();
obj.id = entity.Id;
obj.value = entity.Value;
[..]
return obj;
}
which when I made to
this.convertToSomeOtherObject(entity) {
var converted = entity;
converted.id = entity.Id;
converted.value = entity.Value;
[...]
return converted;
}
solved the problem!
Hopefully this will help someone :)
My extensions to the code.
Source: https://code.google.com/p/gishu-util/source/browse/#git%2FWPF%2FUtilities
Explanatory blog post : http://madcoderspeak.blogspot.com/2010/04/wpf-find-child-control-of-specific-type.html
I m agree with @ReNjITh.R answer but If you want to display error message just beside textbox. Just like below
<html>
<head>
<script type="text/javascript">
function validate()
{
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"/><br>
<input type=button value=check />
</form>
</body>
Add this code after sending message and before getting message from server
recyclerView.scrollToPosition(mChatList.size() - 1);
Servlet is server side technology which is used to create dynamic web page in web application. Actually servlet is an api which consist of group of classes and interfaces, which has some functionality. When we use Servlet API we can use predefined functionality of servlet classes and interfaces.
Lifecycle of Servlet:
Web container maintains the lifecycle of servlet instance.
1 . Servlet class loaded
2 . Servlet instance created
3 . init() method is invoked
4 . service() method invoked
5 . destroy() method invoked
When request raise by client(browser) then web-container checks whether the servlet is running or not if yes then it invoke the service() method and give the response to browser..
When servlet is not running then web-container follow the following steps..
1. classloader load the servlet class
2. Instantiates the servlet
3. Initializes the servlet
4.invoke the service() method
after serving the request web-container wait for specific time, in this time if request comes then it call only service() method otherwise it call destroy() method..
For those still viewing this question on Visual Studio post-2008, a real Edit.Duplicate has been added:
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
For speed, I would do the following, which requires only one pass through each of the two arrays. This method preserves order. I will first present code that does not mutate the original array, then show how it can be easily modified to mutate.
arr = [1,1,1,2,2,3,1]
removals = [1,3,1]
h = removals.group_by(&:itself).transform_values(&:size)
#=> {1=>2, 3=>1}
arr.each_with_object([]) { |n,a|
h.key?(n) && h[n] > 0 ? (h[n] -= 1) : a << n }
#=> [1, 2, 2, 1]
arr
#=> [1, 1, 1, 2, 2, 3, 1]
To mutate arr
write:
h = removals.group_by(&:itself).transform_values(&:count)
arr.replace(arr.each_with_object([]) { |n,a|
h.key?(n) && h[n] > 0 ? (h[n] -= 1) : a << n })
#=> [1, 2, 2, 1]
arr
#=> [1, 2, 2, 1]
This uses the 21st century method Hash#transform_values (new in MRI v2.4), but one could instead write:
h = Hash[removals.group_by(&:itself).map { |k,v| [k,v.size] }]
or
h = removals.each_with_object(Hash.new(0)) { | n,h| h[n] += 1 }
Have you considered using Javascript for this?
$('input').val($('input').val().replace(',', '.'));
UPDATED FOR XCODE 9 (Via Interface Builder)
There's an easier way from the Interface Builder.
Select the UIButton and select this option in the View Utilities > Semantic:
OPTIONAL - 2nd step:
If you want to adjust the spacing between the image and the title you can change the Image Inset here:
Hope that helps!
If I remember correctly, this is the default property for controls.
Can you try by going into Design-View for the admin_reasons that contains the specified Control, then changing the control's Modifiers property to Public or Internal.
SELECT id, 1 AS sort_order
FROM b
UNION
SELECT id, 2 AS sort_order
FROM a
MINUS
SELECT id, 2 AS sort_order
FROM b
ORDER BY 2;
I had a similar issue and found this thread. Replace didn't work for me, and going by the parent was difficult for my situation. Inner Html replaced the children, which wasn't what I wanted either. Using outerHTML got the job done. Hope this helps someone else!
currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>
Modern browsers support JSON.parse()
.
var arr_from_json = JSON.parse( json_string );
In browsers that don't, you can include the json2
library.
In all honesty, a combination of print and print_r() to print out the variables. I know that many prefer to use other more advanced methods but I find this the easiest to use.
I will say that I didn't fully appreciate this until I did some Microprocessor programming at Uni and was not able to use even this.
Or you could use the object tag:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.be">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="http://www.flickr.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->
There is a JSON API for use by mobile applications at http://app.imdb.com
However, the warning is fairly severe:
For use only by clients authorized in writing by IMDb.
Authors and users of unauthorized clients accept full legal exposure/liability for their actions.
I presume this is for those developers that pay for the licence to access the data via their API.
EDIT: Just for kicks, I wrote a client library to attempt to read the data from the API, you can find it here: api-imdb
Obviously, you should pay attention to the warning, and really, use something like TheMovieDB as a better and more open database.
Then you can use this Java API wrapper (that I wrote): api-themoviedb
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
One thing I'll add - I have one of those unique situations.
Using:
deviceId = Secure.getString(this.getContext().getContentResolver(), Secure.ANDROID_ID);
Turns out that even though my Viewsonic G Tablet reports a DeviceID that is not Null, every single G Tablet reports the same number.
Makes it interesting playing "Pocket Empires" which gives you instant access to someone's account based on the "unique" DeviceID.
My device does not have a cell radio.
Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog
instead.
new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
You need to determine whether this is a problem with TortoiseSVN, your Subversion repository, or your network connection.
http://<server>/svn/<module>
and not http://<server>/svn/
usvn
/<module>
. Is that /usvn/
directory suppose to be there?
.size()
is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.
If you'd have jQuery imported and you'd write like $(array).size()
, it would return the array length.
Use >>
instead of >
when directing output to a file:
your_command >> file_to_append_to
If file_to_append_to
does not exist, it will be created.
Example:
$ echo "hello" > file
$ echo "world" >> file
$ cat file
hello
world
This is one of the points in C that can be confusing at first, but the C standard only specifies a minimum range for integer types that is guaranteed to be supported. int
is guaranteed to be able to hold -32767 to 32767, which requires 16 bits. In that case, int
, is 2 bytes. However, implementations are free to go beyond that minimum, as you will see that many modern compilers make int
32-bit (which also means 4 bytes pretty ubiquitously).
The reason your book says 2 bytes is most probably because it's old. At one time, this was the norm. In general, you should always use the sizeof
operator if you need to find out how many bytes it is on the platform you're using.
To address this, C99 added new types where you can explicitly ask for a certain sized integer, for example int16_t
or int32_t
. Prior to that, there was no universal way to get an integer of a specific width (although most platforms provided similar types on a per-platform basis).
You can use Environment Replacement in your Dockerfile
as follows:
ENV PATH="/opt/gtk/bin:${PATH}"
In node.js you can also do the following:
const { promisify } = require('util')
const delay = promisify(setTimeout)
delay(1000).then(() => console.log('hello'))
Try this one:
function show_sub(cat) {
var parent = cat,
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
document.getElementById('cat').onclick = function(){
show_sub(this);
};?
and use this for IE6 & 7
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
Mac OS X and some other Unixes at least have the user path compiled into sshd for security reasons so those of us that install git as /usr/local/git/{bin,lib,...} can run into trouble as the git executables are not in the precompiled path. To override this I prefer to edit my /etc/sshd_config changing:
#PermitUserEnvironment no
to
PermitUserEnvironment yes
and then create ~/.ssh/environment files as needed. My git users have the following in their ~/.ssh/environment file:
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin
Note variable expansion does not occur when the ~/.ssh/environment file is read so:
PATH=$PATH:/usr/local/git/bin
will not work.
Tools --> Options --> Designers node --> Uncheck " Prevent saving changes that require table recreation ".
I had to remove my branch from my command line at:
.git\refs\remotes\{my remote}\{**my branch**}
and then manually doing:
git pull [remote_name] [branch_name]
I was able to pull the changes.
Note: I was using SourceTree and was unable to do the pull.
SELECT *
FROM TableName
WHERE columnNAme IS NULL OR
LTRIM(RTRIM(columnName)) = ''
The fastest way.
Make sure you don't have ROOT app deployed, undeploy if you have one
Rename your war to ROOT.war, deploy, thats all, no configuration changes needed
Just found this one (don't know it, not tested, check yourself)
As you only need this for curiosity you could look into the source of this applet.
It does OCR of handwritten characters with a neural network
If your project is vue-cli and you run npm run build
you should change
assetsPublicPath: '/'
to assetsPublicPath'./'
For Spring Framework users. Using class org.springframework.util.SerializationUtils
:
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T object) {
return (T) SerializationUtils.deserialize(SerializationUtils.serialize(object));
}
i.e. <div tooltip={{ obj.somePropertyThatMayChange }} ...></div>
I had an issue with dynamic tooltips that were not always updating with the view. For example, I was doing something like this:
<div ng-repeat="person in people">
<span data-toggle="tooltip" data-placement="top" title="{{ person.tooltip }}">
{{ person.name }}
</span>
</div>
And activating it as so:
$timeout(function() {
$(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 1500)
However, as my people array would change my tooltips wouldn't always update. I tried every fix in this thread and others with no luck. The glitch seemed to only be happening around 5% of the time, and was nearly impossible to repeat.
Unfortunately, these tooltips are mission critical for my project, and showing an incorrect tooltip could be very bad.
Bootstrap was copying the value of the title
property to a new attribute, data-original-title
and removing the title
property (sometimes) when I would activate the toooltips. However, when my title={{ person.tooltip }}
would change the new value would not always be updated into the property data-original-title
. I tried deactivating the tooltips and reactivating them, destroying them, binding to this property directly... everything. However each of these either didn't work or created new issues; such as the title
and data-original-title
attributes both being removed and un-bound from my object.
Perhaps the most ugly code I've ever pushed, but it solved this small but substantial problem for me. I run this code each time the tooltip is update with new data:
$timeout(function() {
$('[data-toggle="tooltip"]').each(function(index) {
// sometimes the title is blank for no apparent reason. don't override in these cases.
if ($(this).attr("title").length > 0) {
$( this ).attr("data-original-title", $(this).attr("title"));
}
});
$timeout(function() {
// finally, activate the tooltips
$(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 500);
}, 1500);
What's happening here in essence is:
title
s to be updated. title
property that is not empty (i.e. it has changed), copy it to the data-original-title
property so it will be picked up by Bootstrap's toolips.Hope this long answer helps someone who may have been struggling as I was.
Let's assume you have a system where char
is eight bit and all the characters you're trying to count are encoded using a non-negative number. In this case, you can write:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
if ( count[i] != 0) {
printf("The %c. character has %d occurrences.\n", i, counts[i]);
}
}
Note that this will count all the characters in the string. If you are 100% absolutely positively sure that your string will have only letters (no numbers, no whitespace, no punctuation) inside, then 1. asking for "case insensitiveness" starts to make sense, 2. you can reduce the number of entries to the number of characters in the English alphabet (namely 26) and you can write something like this:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}
Just want to point out that this answer provides a better explanation.
Basically you can either have @Getter
and @NoArgConstructor
together
or let Lombok regenerates @ConstructorProperties
using lombok.config
file,
or compile your java project with -parameters
flags,
or let Jackson use Lombok's @Builder
For resolving a single parameter (I guess what's most commonly needed), this is the simplest I found:
build.buildVariableResolver.resolve("myparameter")
in your Groovy System script build step.
You're close
sudo apt-get install php-xml
Then you need to restart apache so it takes effect
sudo service apache2 restart
Use List.AddRange(collection As IEnumerable(Of T)) method.
It allows you to append at the end of your list another collection/list.
Example:
List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);
after hours of googling and trying out different things, this is what fixed it for me:
Make sure there are no certificates in the System > Certificates tab on Keychain Access. Remove all duplicate certificates from there.
Install the WWDR intermediate certificate under certificates from the provisioning portal, in addition to the developers certificates and make sure you see it in the Login > Certificates tab on Keychain Access.
hope this helps some of you!
This method takes all views inside a layout, this is similar to Alexander Kulyakhtin's answer. The difference is, it accepts any type of parent layouts & returns an Array List of views.
public List<View> getAllViews(ViewGroup layout){
List<View> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
views.add(layout.getChildAt(i));
}
return views;
}
This should take care of space, tab and newline:
data = data.replaceAll("[ \t\n\r]*", " ");
the sort method contains an optional argument to pass a custom compare function.
Assuming you wanted an array of arrays:
var arr = [[3, "Mike", 20],[5, "Alex", 15]];
function compareName(a, b)
{
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
arr.sort(compareName);
Otherwise if you wanted an array of objects, you could do:
function compareName(a, b)
{
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
Trying to depict with venn diagrams for better understanding..
Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.
Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.
Inner join : It selects rows that have matching values in both relations.
You can use the SOUNDEX and related DIFFERENCE function in SQL Server to find similar names. The reference on MSDN is here.
In my case, the problem was a conflict of derived dependencies that were been used by other dependencies, and some of those derived dependencies versions were not available, maybe because some deploy that i forgot to do because with workspace resolution everything worked, but when moving to other environment all broke suddenly. And also I was working with version ranges
maven was giving me this error:
Could not resolve dependencies for project MyProject:MyProject:jar:1.0.0: Could not resolve version conflict among Dependency-A:1.0.1 -> Dependency-B:1.1.0 -> Dependency-C:1.0.0, Dependency-X:1.0.1 -> Dependency-Y:1.1.0 -> Dependency-C:1.0.0, Dependency-I:1.0.1 -> Dependency-J:1.1.0 -> Dependency-C:1.0.0
I tried all above and nothing worked, so...
THE SOLUTION: Use LATEST as version in all dependencies, so maven don't need to resolve all dependencies in ranges, wich must be used with care because if you miss to deploy one of the dependencies the build will fail
Only I suggest you to use LATEST if you are working with your own dependencies, otherwise in some third party future version, you could find some compilation or runtime errors
If you want to use an iterator, you can do a placement-new with an array.
std::array<int, 10> icloud = new (cloud) std::array<int,10>;
Note the lack of a ()
at the end, that is important. This creates an array class that uses that memory as its storage, and has STL features like iterators.
(This is C++ TR1/C++11 by the way)
An answer I read on another thread similar to this one that worked for me when I had this problem involved the layout xml.
Your logcat says "No view found for id 0x7f080011".
Open up the gen->package->R.java->id
and then look for id 0x7f080011
.
When I had this problem, this id belonged to a FrameLayout
in my activity_main.xml
file.
The FrameLayout did not have an ID (there was no statement android:id = "blablabla"
).
Make sure that all of your components in all of your layouts have IDs, particularly the component cited in the logcat.
Using list comprehension,
[a for a in os.listdir() if os.path.isdir(a)]
I think It is the simplest way
I don't know what you imagine when you say "beautiful", but what about this? I personally think it's worse than the classic form you posted, but somebody might like it...
if (str instanceof String == false) { /* ... */ }
Below is code to put your Linearlayout at bottom and put its content at center. You have to use RelativeLayout to set Layout at bottom.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#97611F"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="View Saved Searches"
android:textSize="15dp"
android:textColor="#fff"
android:gravity="center_vertical"
android:visibility="visible" />
<TextView
android:layout_width="30dp"
android:layout_height="24dp"
android:text="12"
android:textSize="12dp"
android:textColor="#fff"
android:gravity="center_horizontal"
android:padding="1dp"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
Try passing the password for the key and store as part of the command
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -keypass android -storepass android \
| openssl sha1 -binary \
| openssl base64
You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.
Note that if you use SELECT FOR UPDATE
to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog
option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE
, then to check the affected row count.
add below line to my.cnf
file
innodb_locks_unsafe_for_binlog = 1
#1 - ON
0 - OFF
jminix is an embedded web based JMX console. Not sure if it's maintained any longer, but still.
This solution is working with Android Studio 4.0.1.
Apart from creating a new module as suggested in above solution, you can try this solution.
If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.
In your root project build.gradle
add
repositories {
flatDir {
dirs 'libs'
}}
Then in the module where you want to add the .aar file locally. simply add below lines of code.
dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')
}
Happy Coding :)
As a db driver, there is also oursql. Some of the reasons listed on that link, which say why oursql is better:
- oursql has real parameterization, sending the SQL and data to MySQL completely separately.
- oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
- oursql can both insert rows lazily and fetch rows lazily.
- oursql has unicode support on by default.
- oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
- oursql runs natively on python 3.x.
Very similar to mysqldb:
import oursql
db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
print row[0]
The tutorial in the documentation is pretty decent.
And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.
You can do in the following case,
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR FirstName = @FirstName) AND
(@LastNameName IS NULL OR LastName = @LastName) AND
(@Title IS NULL OR Title = @Title)
END
however depend on data sometimes better create dynamic query and execute them.
The simpliest way
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60)%60;
int hours = (s/60)/60;
System.out.println(hours + ":" + min + ":" + sec);
Just use plain objects:
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
[[]]*3
is not the same as [[], [], []]
.
It's as if you'd said
a = []
listy = [a, a, a]
In other words, all three list references refer to the same list instance.
Either you can Downgrade to JRE 1.7.49
or if you want to run on JRE 8
Step to fix:-
Go to Lib folder of Liferay Tomcat .
Replace :- ecj-3.7.2.jar with ecj-4.4.2.
Restart the Server
To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then apply it to your dataframe passing in the axis=1
option:
In [1]: df['C'] = df.apply(f, axis=1)
In [2]: df
Out[2]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.
Edit
Here is the vectorized version
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
Not sure why this isn't implemented directly in R, but this answer is essentially the same as Andrii's and Wordsforthewise, I just turned into a function for the sake of convenience if somebody uses it a lot like me.
r2_general <-function(preds,actual){
return(1- sum((preds - actual) ^ 2)/sum((actual - mean(actual))^2))
}
It is possibly to use the flag -o,--offline "Work offline"
to prevent that.
Like this:
maven compile -o
Regarding a previous answer, setting html
and body
to height: 100%
doesn't seem to work if the content needs to scroll. Adding fixed
to the background seems to fix that - no need for height: 100%;
E.g.:
body {_x000D_
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8)) fixed;_x000D_
}
_x000D_
This post aims to give readers a primer on SQL-flavored merging with pandas, how to use it, and when not to use it.
In particular, here's what this post will go through:
The basics - types of joins (LEFT, RIGHT, OUTER, INNER)
What this post (and other posts by me on this thread) will not go through:
Note
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.Furthermore, all the DataFrames here can be copied and replicated so you can play with them. Also, see this post on how to read DataFrames from your clipboard.
Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from here.
merge
!np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
left
key value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right
key value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
For the sake of simplicity, the key column has the same name (for now).
An INNER JOIN is represented by
Note
This, along with the forthcoming figures all follow this convention:
- blue indicates rows that are present in the merge result
- red indicates rows that are excluded from the result (i.e., removed)
- green indicates missing values that are replaced with
NaN
s in the result
To perform an INNER JOIN, call merge
on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.
left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
This returns only rows from left
and right
which share a common key (in this example, "B" and "D).
A LEFT OUTER JOIN, or LEFT JOIN is represented by
This can be performed by specifying how='left'
.
left.merge(right, on='key', how='left')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
Carefully note the placement of NaNs here. If you specify how='left'
, then only keys from left
are used, and missing data from right
is replaced by NaN.
And similarly, for a RIGHT OUTER JOIN, or RIGHT JOIN which is...
...specify how='right'
:
left.merge(right, on='key', how='right')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
2 E NaN 0.950088
3 F NaN -0.151357
Here, keys from right
are used, and missing data from left
is replaced by NaN.
Finally, for the FULL OUTER JOIN, given by
specify how='outer'
.
left.merge(right, on='key', how='outer')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
4 E NaN 0.950088
5 F NaN -0.151357
This uses the keys from both frames, and NaNs are inserted for missing rows in both.
The documentation summarizes these various merges nicely:
If you need LEFT-Excluding JOINs and RIGHT-Excluding JOINs in two steps.
For LEFT-Excluding JOIN, represented as
Start by performing a LEFT OUTER JOIN and then filtering (excluding!) rows coming from left
only,
(left.merge(right, on='key', how='left', indicator=True)
.query('_merge == "left_only"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
Where,
left.merge(right, on='key', how='left', indicator=True)
key value_x value_y _merge
0 A 1.764052 NaN left_only
1 B 0.400157 1.867558 both
2 C 0.978738 NaN left_only
3 D 2.240893 -0.977278 both
And similarly, for a RIGHT-Excluding JOIN,
(left.merge(right, on='key', how='right', indicator=True)
.query('_merge == "right_only"')
.drop('_merge', 1))
key value_x value_y
2 E NaN 0.950088
3 F NaN -0.151357
Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an ANTI-JOIN),
You can do this in similar fashion—
(left.merge(right, on='key', how='outer', indicator=True)
.query('_merge != "both"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
4 E NaN 0.950088
5 F NaN -0.151357
If the key columns are named differently—for example, left
has keyLeft
, and right
has keyRight
instead of key
—then you will have to specify left_on
and right_on
as arguments instead of on
:
left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)
left2
keyLeft value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right2
keyRight value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
keyLeft value_x keyRight value_y
0 B 0.400157 B 1.867558
1 D 2.240893 D -0.977278
When merging on keyLeft
from left
and keyRight
from right
, if you only want either of the keyLeft
or keyRight
(but not both) in the output, you can start by setting the index as a preliminary step.
left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
value_x keyRight value_y
0 0.400157 B 1.867558
1 2.240893 D -0.977278
Contrast this with the output of the command just before (that is, the output of left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
), you'll notice keyLeft
is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.
DataFrames
For example, consider
right3 = right.assign(newcol=np.arange(len(right)))
right3
key value newcol
0 B 1.867558 0
1 D -0.977278 1
2 E 0.950088 2
3 F -0.151357 3
If you are required to merge only "new_val" (without any of the other columns), you can usually just subset columns before merging:
left.merge(right3[['key', 'newcol']], on='key')
key value newcol
0 B 0.400157 0
1 D 2.240893 1
If you're doing a LEFT OUTER JOIN, a more performant solution would involve map
:
# left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
As mentioned, this is similar to, but faster than
left.merge(right3[['key', 'newcol']], on='key', how='left')
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
To join on more than one column, specify a list for on
(or left_on
and right_on
, as appropriate).
left.merge(right, on=['key1', 'key2'] ...)
Or, in the event the names are different,
left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])
merge*
operations and functionsMerging a DataFrame with Series on index: See this answer.
Besides merge
, DataFrame.update
and DataFrame.combine_first
are also used in certain cases to update one DataFrame with another.
pd.merge_ordered
is a useful function for ordered JOINs.
pd.merge_asof
(read: merge_asOf) is useful for approximate joins.
This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the documentation on merge
, join
, and concat
as well as the links to the function specs.
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
32-bit
%windir%\Microsoft.NET\Framework\[version]\config\machine.config
64-bit
%windir%\Microsoft.NET\Framework64\[version]\config\machine.config
[version]
should be equal to v1.0.3705
, v1.1.4322
, v2.0.50727
or v4.0.30319
.
v3.0
and v3.5
just contain additional assemblies to v2.0.50727
so there should be no config\machine.config
. v4.5.x
and v4.6.x
are stored inside v4.0.30319
.
InvalidOperationException- An InvalidOperationException has occurred. It reports a "collection was modified" in a foreach-loop
Use break statement, Once the object is removed.
ex:
ArrayList list = new ArrayList();
foreach (var item in list)
{
if(condition)
{
list.remove(item);
break;
}
}
This is a simple loop that keeps prompting unless the user selects 'y' or 'n'
$confirmation = Read-Host "Ready? [y/n]"
while($confirmation -ne "y")
{
if ($confirmation -eq 'n') {exit}
$confirmation = Read-Host "Ready? [y/n]"
}
If you want the effect of a nested for loop, use:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x
and y
are not the same length, zip
will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest
.
UPDATE
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip
or product
. I think they want a set
:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection
method of a set
will return all the elements common to it and another set (Note that if your lists contains other list
s, you might want to convert the inner list
s to tuples
first so that they are hashable; otherwise the call to set
will fail.). The list
function then turns the set back into a list.
UPDATE 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip
would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
If you have the ID of the div, try this:
<input type='submit' onclick='$("#div_id").show()'>
I have been struggling on this issue for two days, sharing my solution here in case anyone may need it.
The VMs that I'm using are Standard N-series GPU server with 2 K80 cards on Azure platform. With Ubuntu 18.04 OS installed.
Apparently there is an update of linux kernel several days before I came across this issue, and after the update the driver stopped working.
At first, I did purge and re-install as above replies suggested. Nothing works. Out of sudden(I don't remember why I wanted to do it), I updated the default gcc and g++ version on one of my VM as following.
sudo apt install software-properties-common
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 90
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-9 90
Then I purged the nvidia softwares and reinstall it as instructed in official document(please choose the correct one for your system: https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1804&target_type=deblocal) again.
sudo apt-get purge nvidia-*
Then the nvidia-smi command finally worked again.
PS:
If you are using Azure linux VM like me. The recommended way to install CUDA is actually by enabling "NVIDIA GPU Driver Extension" in the Azure portal (of course, after you have configured the correct gcc version).
I have tried this way on my another VM and It works as well.
A little bit late, but if it helps, this works for me...
XmlNodeList NodoEstudios = DocumentoXML.SelectNodes("//ALUMNOS/ALUMNO[@id=\"" + Id + "\"]/estudios");
string Proyecto = "";
foreach(XmlElement ElementoProyecto in NodoEstudios)
{
XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName("proyecto");
Proyecto = (EleProyecto[0] == null)?"": EleProyecto[0].InnerText;
}
1.create a lib folder in your project file,
2.copy your jarFiles to the lib folder
3.right click on to your jarFile go to build path>Add to build path (now your jar file is part of your refrerenced libraries )
4.open command prompt and navigate to your project directory and write
mvn install: install-file "-Dfile=<yourJarFileName>.jar" "-DgroupId=<yourGroupID>" "-DartifactId=<yourArtifactId>" "-Dversion=<yourVersion>" "-Dpackaging=jar"
6.Rebuild your local repository index by opening in eclipse- go to window>show view>other>maven>maven Repositories. Right click on local Repositores and hit "RebuildIndex"
5.open your pom.xml file and add your dependency
<dependency>
<groupId><yourGroupID></groupId>
<artifactId><yourArtifactId></artifactId>
<version><yourVersion></version>
</dependency>
and run
mvn clean
mvn compile
mvn test
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = 'TABLE_NAME'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;
Make sure that 'TABLE_NAME' is in upper case since Oracle stores table names in upper case.
It's not that you're actually getting extra precision - it's that the float didn't accurately represent the number you were aiming for originally. The double is representing the original float accurately; toString
is showing the "extra" data which was already present.
For example (and these numbers aren't right, I'm just making things up) suppose you had:
float f = 0.1F;
double d = f;
Then the value of f
might be exactly 0.100000234523. d
will have exactly the same value, but when you convert it to a string it will "trust" that it's accurate to a higher precision, so won't round off as early, and you'll see the "extra digits" which were already there, but hidden from you.
When you convert to a string and back, you're ending up with a double value which is closer to the string value than the original float was - but that's only good if you really believe that the string value is what you really wanted.
Are you sure that float/double are the appropriate types to use here instead of BigDecimal
? If you're trying to use numbers which have precise decimal values (e.g. money), then BigDecimal
is a more appropriate type IMO.
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
I created a PS script to check idle time and jiggle the mouse to prevent the screensaver.
There are two parameters you can control how it works.
$checkIntervalInSeconds
: the interval in seconds to check if the idle time exceeds the limit
$preventIdleLimitInSeconds
: the idle time limit in seconds. If the idle time exceeds the idle time limit, jiggle the mouse to prevent the screensaver
Here we go. Save the script in preventIdle.ps1
. For preventing the 4-min screensaver, I
set $checkIntervalInSeconds = 30
and $preventIdleLimitInSeconds = 180
.
Add-Type @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PInvoke.Win32 {
public static class UserInput {
[DllImport("user32.dll", SetLastError=false)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO {
public uint cbSize;
public int dwTime;
}
public static DateTime LastInput {
get {
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
return lastInput;
}
}
public static TimeSpan IdleTime {
get {
return DateTime.UtcNow.Subtract(LastInput);
}
}
public static double IdleSeconds {
get {
return IdleTime.TotalSeconds;
}
}
public static int LastInputTicks {
get {
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
GetLastInputInfo(ref lii);
return lii.dwTime;
}
}
}
}
'@
Add-Type @'
using System;
using System.Runtime.InteropServices;
namespace MouseMover
{
public class MouseSimulator
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
public SendInputEventType type;
public MouseKeybdhardwareInputUnion mkhi;
}
[StructLayout(LayoutKind.Explicit)]
struct MouseKeybdhardwareInputUnion
{
[FieldOffset(0)]
public MouseInputData mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
struct MouseInputData
{
public int dx;
public int dy;
public uint mouseData;
public MouseEventFlags dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[Flags]
enum MouseEventFlags : uint
{
MOUSEEVENTF_MOVE = 0x0001
}
enum SendInputEventType : int
{
InputMouse
}
public static void MoveMouseBy(int x, int y) {
INPUT mouseInput = new INPUT();
mouseInput.type = SendInputEventType.InputMouse;
mouseInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_MOVE;
mouseInput.mkhi.mi.dx = x;
mouseInput.mkhi.mi.dy = y;
SendInput(1, ref mouseInput, Marshal.SizeOf(mouseInput));
}
}
}
'@
$checkIntervalInSeconds = 30
$preventIdleLimitInSeconds = 180
while($True) {
if (([PInvoke.Win32.UserInput]::IdleSeconds -ge $preventIdleLimitInSeconds)) {
[MouseMover.MouseSimulator]::MoveMouseBy(10,0)
[MouseMover.MouseSimulator]::MoveMouseBy(-10,0)
}
Start-Sleep -Seconds $checkIntervalInSeconds
}
Then, open Windows PowerShell and run
powershell -ExecutionPolicy ByPass -File C:\SCRIPT-DIRECTORY-PATH\preventIdle.ps1
On Debian/Ubuntu:
aptitude install python-numpy
On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
Sometimes you must change the name (or check to get it automatically from compiler).
Example:
Filename = amp2-rot.png
It is not working as:
PictureBoxName.Image = resources.GetObject("amp2-rot.png")
It works, just as amp2_rot
for me:
PictureBox_L1.Image = My.Resources.Resource.amp2_rot
Assuming your table of data is called ProjectInfo:
SELECT DISTINCT Contract, Activity
FROM ProjectInfo
WHERE Contract = (SELECT Contract
FROM (SELECT DISTINCT Contract, Activity
FROM ProjectInfo) AS ContractActivities
GROUP BY Contract
HAVING COUNT(*) = 1);
The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.
Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.
I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:
<style type="text/css">
/* default styles here for older browsers.
I tend to go for a 600px - 960px width max but using percentages
*/
@media only screen and (min-width: 960px) {
/* styles for browsers larger than 960px; */
}
@media only screen and (min-width: 1440px) {
/* styles for browsers larger than 1440px; */
}
@media only screen and (min-width: 2000px) {
/* for sumo sized (mac) screens */
}
@media only screen and (max-device-width: 480px) {
/* styles for mobile browsers smaller than 480px; (iPhone) */
}
@media only screen and (device-width: 768px) {
/* default iPad screens */
}
/* different techniques for iPad screening */
@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
/* For portrait layouts only */
}
@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
/* For landscape layouts only */
}
</style>
But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.
Also! If you're looking for printability you can use @media print{}
What happens when you set all of the attributes in one attr()
command like so
$(this).attr({
id : this.id + '_' + new_id,
name: this.name + '_' + new_id,
value: 'test'
});
Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx
EDIT:
You need to put the protocol prefix in front the address, i.e. in your case "ftp://"
I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event)
and getEvents(Node elm)
which you can utilize. Be aware that it modifies the EventTarget
prototype method add/RemoveEventListener
, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ...
Script:
var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();
Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.
String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
.replace("-----END RSA PRIVATE KEY-----", "");
// Base64 decode the data
byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);
try {
ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
.fromByteArray(encodedPrivateKey);
Enumeration<?> e = primitive.getObjects();
BigInteger v = ((DERInteger) e.nextElement()).getValue();
int version = v.intValue();
if (version != 0 && version != 1) {
throw new IllegalArgumentException("wrong version for RSA private key");
}
/**
* In fact only modulus and private exponent are in use.
*/
BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
throw new IllegalStateException(e);
}
If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.
Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.
Above description is taken from MYSQL official website.
Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.
Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.
—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:
{{#variable}}<span class="text">{{.}}</span>{{/variable}}
if you wanna remove the last one just do your_list.pop(-1)
if you wanna remove the first one your_list.pop(0)
or any index you wish to remove
We had the same problem and you have to use
git fetch
git push origin branch_name
git branch -r
Hope this help someone facing the same problem
I got the answer to my own question, ant this is:
select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))
Where N is the number of characters to remove. This avoids to write the complex column/string twice
Also some of common cases :
maybe you export class with "default" prefix like so
export default class Module {}
just remove it
export class Module {}
this is solve the issue for me
I realize this post is old but I wanted to add that I had to take an extra step to get this to work.
Instead of just doing:
pip install pywin32
I had use use the -m
flag to get this to work properly. Without it I was running into an issue where I was still getting the error ImportError: No module named win32com
.
So to fix this you can give this a try:
python -m pip install pywin32
This worked for me and has worked on several version of python where just doing pip install pywin32
did not work.
Versions tested on:
3.6.2, 3.7.6, 3.8.0, 3.9.0a1.
First Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create a pointer that points to random memory address
*ptr = 20; //Dereference that pointer,
// and assign a value to random memory address.
//Depending on external (not inside your program) state
// this will either crash or SILENTLY CORRUPT another
// data structure in your program.
printf("%d", *ptr); //Print contents of same random memory address
// May or may not crash, depending on who owns this address
return 0;
}
Second Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create pointer to random memory address
int q = 50; //Create local variable with contents int 50
ptr = &q; //Update address targeted by above created pointer to point
// to local variable your program properly created
printf("%d", *ptr); //Happily print the contents of said local variable (q)
return 0;
}
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.
Use torch.unsqueeze(input, dim, out=None)
>>> import torch
>>> a = torch.Tensor([1,2,3,4,5])
>>> a
1
2
3
4
5
[torch.FloatTensor of size 5]
>>> a = a.unsqueeze(0)
>>> a
1 2 3 4 5
[torch.FloatTensor of size 1x5]
It's more readable a single try catch block. If its important identify a kind of error I recommend customize your Exceptions.
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
$tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (TableAException $e){
throw $e;
} catch (Exception $e) {
throw $e;
}
You should add user settings:
{
"editor.showFoldingControls": "always",
"editor.folding": true,
"editor.foldingStrategy": "indentation",
}
Xamarin
Label.Font = UIFont.FromName("Copperplate", 10.0f);
Swift
text.font = UIFont.init(name: "Poppins-Regular", size: 14)
To get the list of font family Github/IOS-UIFont-Names
How about this, which I managed to achieve thanks, in part, to this post.
You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE
), inside several directories with a pattern (e.g. /logsapp1, /logsapp2
).
Each file has a pattern you want to grep (e.g. "init time"
), and you want to have the "init time"
of each file, but knowing which file it belongs to.
find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt
Then the outputfilename.txt
would be something like
./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms
In general
find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt
Explanation:
find
command will search the filenames based in the pattern
then, pipe xargs -I{}
will redirect the find
output to the {}
which will be the input for grep ""pattern" {}
Then the trick to make grep
display the filenames \dev\null
and finally, write the output in file with tee outputfile.txt
This worked for me in grep
version 9.0.5 build 1989.
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
2-3 months to learn the basics...no way. Unless you're gonna code spaghetti sure. Same goes for the 1-2 years. Spaghetti it is then..
double r2()
{
return (rand() % 10001) / 10000.0;
}
On Xamarin.Android, It works for me and need change layout
var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
layout.SpanCount = GetItemPerRow(Context);
recyclerView.SetAdapter(null);
recyclerView.SetAdapter(adapter); //reset
SQL
SQL is used to communicate with a database, it is the standard language for relational database management systems.
In detail Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).
Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.
PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation
Specialities of PL/SQL
T-SQL
Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL
The Structured Query Language or SQL is a programming language that focuses on managing relational databases. SQL has its own limitations which spurred the software giant Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL. Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.
T-SQL adds a number of features that are not available in SQL.
This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.
Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.
Choosing between T-SQL and SQL is all up to the user. Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.
References , Wikipedea , Tutorial Points :www.differencebetween.com
The problem, in my case, was that I was using Amazon's Cloudflare and Cloudfront's Cloudfront in tandem, and Cloudfront did not like the settings that I had provided Cloudflare.
More specifically, in the Crypto settings on Cloudflare, I had set the "Minimum TLS Settings" to 1.2, without enabling the TLS 1.2 communication setting for the distribution in Cloudfront. This was enough to make Cloudfront declare a 502 Bad Gateway error when it tried to connect to the Cloudflare-protected server.
To fix this, I had to disable SSLv3 support in the Origin Settings for that Cloudfront distribution, and enable TLS 1.2 as a supported protocol for that origin server.
To debug this problem, I used command-line versions of curl, to see what Cloudfront was actually returning when you asked for an image from its CDN, and I also used the command-line version of openssl, to determine exactly which protocols Cloudflare was offering (it wasn't offering TLS 1.0).
tl:dr; make sure everything accepts and asks for TLS 1.2, or whatever latest and greatest TLS everyone is using by the time you read this.
If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:
mysql -h localhost -P 3306 --protocol=tcp -u root
Change 3306 to port number you have forwarded from Docker container (in your case it will be 12345).
Because you are running MySQL inside Docker container, socket is not available and you need to connect through TCP. Setting "--protocol" in the mysql command will change that.
A little bit late for the party, but it's an interessting question.
You can write your own inc.bat for incrementing a number.
It can increment numbers from 0 to 9998.
@echo off
if "%1"==":inc" goto :increment
call %0 :inc %counter0%
set counter0=%_cnt%
if %_overflow%==0 goto :exit
call %0 :inc %counter1%
set counter1=%_cnt%
if %_overflow%==0 goto :exit
call %0 :inc %counter2%
set counter2=%_cnt%
if %_overflow%==0 goto :exit
call %0 :inc %counter3%
set counter3=%_cnt%
goto :exit
:increment
set _overflow=0
set _cnt=%2
if "%_cnt%"=="" set _cnt=0
if %_cnt%==9 goto :overflow
if %_cnt%==8 set _cnt=9
if %_cnt%==7 set _cnt=8
if %_cnt%==6 set _cnt=7
if %_cnt%==5 set _cnt=6
if %_cnt%==4 set _cnt=5
if %_cnt%==3 set _cnt=4
if %_cnt%==2 set _cnt=3
if %_cnt%==1 set _cnt=2
if %_cnt%==0 set _cnt=1
goto :exit
:overflow
set _cnt=0
set _overflow=1
goto :exit
:exit
set count=%counter3%%counter2%%counter1%%counter0%
A sample for using it is here
@echo off
set counter0=0
set counter1=
set counter2=
set counter3=
:loop
call inc.bat
echo %count%
if not %count%==250 goto :loop
Some additions to a given set of answers:
First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.
It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )
# you need me-redis and awesome-print gems to run exact code
redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new
=> #<Redis client v4.0.1 for redis://127.0.0.1:6379/0>
> redis.flushdb
=> "OK"
> ap redis.info(:memory)
{
"used_memory" => "529512",
**"used_memory_human" => "517.10K"**,
....
}
=> nil
# me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )
# txt is some english fictionary book around 56K length,
# so we just take some random 63-symbols string from it
> redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
=> :done
> ap redis.info(:memory)
{
"used_memory" => "1251944",
**"used_memory_human" => "1.19M"**, # ~ 72b per key/value
.....
}
> redis.flushdb
=> "OK"
# setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte
> redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done
> ap redis.info(:memory)
{
"used_memory" => "1876064",
"used_memory_human" => "1.79M", # ~ 134 bytes per pair
....
}
redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
ap redis.info(:memory)
{
"used_memory" => "2262312",
"used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes
....
}
For TheHippo answer, comments on Option one are misleading:
hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.
For BMiner answer.
Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!
But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much
But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.
Second option will most likely go to the fourth solution under a hood because as question states:
Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.
And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.
My suggestion how to optimize such dataset:
You've got two options:
If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.
If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.
You have to use the encoding as latin1 to read this file as there are some special character in this file, use the below code snippet to read the file.
The problem here is the encoding type. When Python can't convert the data to be read, it gives an error.
You can you latin1 or other encoding values.
I say try and test to find the right one for your dataset.
The local names for a function are decided when the function is defined:
>>> x = 1
>>> def inc():
... x += 5
...
>>> inc.__code__.co_varnames
('x',)
In this case, x
exists in the local namespace. Execution of x += 5
requires a pre-existing value for x
(for integers, it's like x = x + 5
), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError
is named as such.
Compare the other version, where x
is not a local variable, so it can be resolved at the global scope instead:
>>> def incg():
... print(x)
...
>>> incg.__code__.co_varnames
()
Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
My solution is:
$maxs = array_keys($array, max($array))
Note:
this way you can retrieve every key related to a given max value.
If you are interested only in one key among all simply use $maxs[0]
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
You can use git reset --soft
to change the version you want to have as parent for the changes you have in your index and working tree. The cases where this is useful are rare. Sometimes you might decide that the changes you have in your working tree should belong onto a different branch. Or you can use this as a simple way to collapse several commits into one (similar to squash/fold).
See this answer by VonC for a practical example: Squash the first two commits in Git?
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float:
territory):
<br />s
to split the options apart and some CSS to vertically align them:<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
Styling the <label>
is why you'll need to resort to Javascript. A library like jQuery
is perfect for this:
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
The focus
and blur
hooks are needed to make this work in IE.
There are a few decompilers out there... A quick search yields:
And many more.
These produce Java code. Java comes with something that lets you see JVM byte code (javap).
The following script will help u to go to a process if that script exist in a specified variable,
cat > waitfor.csh
#!/bin/csh
while !( -e $1 )
sleep 10m
end
ctrl+D
here -e
is for working with files,
$1
is a shell variable,
sleep for 10 minutes
u can execute the script by ./waitfor.csh ./temp ; echo "the file exits"
If you updated the android SDK, the licenses may have changed. Depending on how you did the update you may or may not have been prompted to accept the changes, or maybe it just doesn't save the fact that you did accept them in a way flutter can understand.
To resolve, try running
flutter doctor --android-licenses
This should prompt you to accept licenses (it may ask you first, in case just type y
and press enter - although it should tell you that).
If you still have problems after doing that, it might be worth either opening a new bug in the Flutter Github repository, or adding a comment on an existing issue like this one as it may be what you're seeing.
To import files from OS X Finder into Android Studio, just drag the relevant files to your resource folder.
Don't find a permanent config option for this, but this is the workaround I'm using
Using %
will help you to do this...
You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:
odd function:
var isOdd = function(num) {
return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};
even function:
var isEven = function(num) {
return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};
and call it like this:
isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true
desc 'an updated version'
task :task_name, [:arg1, :arg2] => [:dependency1, :dependency2] do |t, args|
puts args[:arg1]
end
I needed to perform a search on a large object and return the addresses of the matches, not just the matched values themselves.
This function searches an object for a string (or alternatively, uses a callback function to perform custom logic) and keeps track of where the value was found within the object. It also avoids circular references.
//Search function_x000D_
var locateInObject = function(obj, key, find, result, currentLocation){_x000D_
if(obj === null) return;_x000D_
result = result||{done:[],found:{}};_x000D_
if(typeof obj == 'object'){_x000D_
result.done.push(obj);_x000D_
}_x000D_
currentLocation = currentLocation||key;_x000D_
var keys = Object.keys(obj);_x000D_
for(var k=0; k<keys.length; ++k){_x000D_
var done = false;_x000D_
for(var d=0; d<result.done.length; ++d){_x000D_
if(result.done[d] === obj[keys[k]]){_x000D_
done = true;_x000D_
break;_x000D_
}_x000D_
}_x000D_
if(!done){_x000D_
var location = currentLocation+'.'+keys[k];_x000D_
if(typeof obj[keys[k]] == 'object'){_x000D_
locateInObject(obj[keys[k]], keys[k], find, result, location)_x000D_
}else if((typeof find == 'string' && obj[keys[k]].toString().indexOf(find) > -1) || (typeof find == 'function' && find(obj[keys[k]], keys[k]))){_x000D_
result.found[location] = obj[keys[k]];_x000D_
}_x000D_
}_x000D_
}_x000D_
return result.found;_x000D_
}_x000D_
_x000D_
//Test data_x000D_
var test = {_x000D_
key1: {_x000D_
keyA: 123,_x000D_
keyB: "string"_x000D_
},_x000D_
key2: {_x000D_
keyC: [_x000D_
{_x000D_
keyI: "string123",_x000D_
keyII: 2.3_x000D_
},_x000D_
"string"_x000D_
],_x000D_
keyD: null_x000D_
},_x000D_
key3: [_x000D_
1,_x000D_
2,_x000D_
123,_x000D_
"testString"_x000D_
],_x000D_
key4: "123string"_x000D_
}_x000D_
//Add a circular reference_x000D_
test.key5 = test;_x000D_
_x000D_
//Tests_x000D_
console.log(locateInObject(test, 'test', 'string'))_x000D_
console.log(locateInObject(test, 'test', '123'))_x000D_
console.log(locateInObject(test, 'test', function(val, key){ return key.match(/key\d/) && val.indexOf('string') > -1}))
_x000D_
On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.
But, What if you want to destroy the token on the Node server -
The problem with JWT package is that it doesn't provide any method or way to destroy the token.
So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT
This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method
it works in this way :
1) Install jwt-redis from npm
2) To Create -
var redis = require('redis');
var JWTR = require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);
jwtr.sign(payload, secret)
.then((token)=>{
// your code
})
.catch((error)=>{
// error handling
});
3) To verify -
jwtr.verify(token, secret);
4) To Destroy -
jwtr.destroy(token)
Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.
I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-
def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
if string[y]==" ":
list_.append(string[x:y])
x = y+1
elif y==len(string)-1:
list_.append(string[x:y+1])
return list_
def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
reversed_list.append(element)
return reversed_list
def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with
space as a separator'''
final_string = str()
for element in list_:
final_string += str(element) + " "
return final_string
#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I
Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!
You should try it like this:
var result =
from priceLog in PriceLogList
group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
select new {
LogDateTime = dateGroup.Key,
AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
};
if we are using JpaRepository then it will internally created the queries.
Sample
findByLastnameAndFirstname(String lastname,String firstname)
findByLastnameOrFirstname(String lastname,String firstname)
findByStartDateBetween(Date date1,Date2)
findById(int id)
Note
if suppose we need complex queries then we need to write manual queries like
@Query("SELECT salesOrder FROM SalesOrder salesOrder WHERE salesOrder.clientId=:clientId AND salesOrder.driver_username=:driver_username AND salesOrder.date>=:fdate AND salesOrder.date<=:tdate ")
@Transactional(readOnly=true)
List<SalesOrder> findAllSalesByDriver(@Param("clientId")Integer clientId, @Param("driver_username")String driver_username, @Param("fdate") Date fDate, @Param("tdate") Date tdate);
There are two big considerations that the original poster needs to consider:
{'a_b':{'c':1}, 'a':{'b_c':2}}
would result in {'a_b_c':???}
. The below solution evades the problem by returning an iterable of pairs.joinedKey = '_'.join(*keys)
, that will cost you O(N^2) running time. However if you're willing to say nextKey = previousKey+'_'+thisKey
, that gets you O(N) time. The solution below lets you do both (since you could merely concatenate all the keys, then postprocess them).(Performance is not likely an issue, but I'll elaborate on the second point in case anyone else cares: In implementing this, there are numerous dangerous choices. If you do this recursively and yield and re-yield, or anything equivalent which touches nodes more than once (which is quite easy to accidentally do), you are doing potentially O(N^2) work rather than O(N). This is because maybe you are calculating a key a
then a_1
then a_1_i
..., and then calculating a
then a_1
then a_1_ii
..., but really you shouldn't have to calculate a_1
again. Even if you aren't recalculating it, re-yielding it (a 'level-by-level' approach) is just as bad. A good example is to think about the performance on {1:{1:{1:{1:...(N times)...{1:SOME_LARGE_DICTIONARY_OF_SIZE_N}...}}}}
)
Below is a function I wrote flattenDict(d, join=..., lift=...)
which can be adapted to many purposes and can do what you want. Sadly it is fairly hard to make a lazy version of this function without incurring the above performance penalties (many python builtins like chain.from_iterable aren't actually efficient, which I only realized after extensive testing of three different versions of this code before settling on this one).
from collections import Mapping
from itertools import chain
from operator import add
_FLAG_FIRST = object()
def flattenDict(d, join=add, lift=lambda x:x):
results = []
def visit(subdict, results, partialKey):
for k,v in subdict.items():
newKey = lift(k) if partialKey==_FLAG_FIRST else join(partialKey,lift(k))
if isinstance(v,Mapping):
visit(v, results, newKey)
else:
results.append((newKey,v))
visit(d, results, _FLAG_FIRST)
return results
To better understand what's going on, below is a diagram for those unfamiliar with reduce
(left), otherwise known as "fold left". Sometimes it is drawn with an initial value in place of k0 (not part of the list, passed into the function). Here, J
is our join
function. We preprocess each kn with lift(k)
.
[k0,k1,...,kN].foldleft(J)
/ \
... kN
/
J(k0,J(k1,J(k2,k3)))
/ \
/ \
J(J(k0,k1),k2) k3
/ \
/ \
J(k0,k1) k2
/ \
/ \
k0 k1
This is in fact the same as functools.reduce
, but where our function does this to all key-paths of the tree.
>>> reduce(lambda a,b:(a,b), range(5))
((((0, 1), 2), 3), 4)
Demonstration (which I'd otherwise put in docstring):
>>> testData = {
'a':1,
'b':2,
'c':{
'aa':11,
'bb':22,
'cc':{
'aaa':111
}
}
}
from pprint import pprint as pp
>>> pp(dict( flattenDict(testData, lift=lambda x:(x,)) ))
{('a',): 1,
('b',): 2,
('c', 'aa'): 11,
('c', 'bb'): 22,
('c', 'cc', 'aaa'): 111}
>>> pp(dict( flattenDict(testData, join=lambda a,b:a+'_'+b) ))
{'a': 1, 'b': 2, 'c_aa': 11, 'c_bb': 22, 'c_cc_aaa': 111}
>>> pp(dict( (v,k) for k,v in flattenDict(testData, lift=hash, join=lambda a,b:hash((a,b))) ))
{1: 12416037344,
2: 12544037731,
11: 5470935132935744593,
22: 4885734186131977315,
111: 3461911260025554326}
Performance:
from functools import reduce
def makeEvilDict(n):
return reduce(lambda acc,x:{x:acc}, [{i:0 for i in range(n)}]+range(n))
import timeit
def time(runnable):
t0 = timeit.default_timer()
_ = runnable()
t1 = timeit.default_timer()
print('took {:.2f} seconds'.format(t1-t0))
>>> pp(makeEvilDict(8))
{7: {6: {5: {4: {3: {2: {1: {0: {0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0}}}}}}}}}
import sys
sys.setrecursionlimit(1000000)
forget = lambda a,b:''
>>> time(lambda: dict(flattenDict(makeEvilDict(10000), join=forget)) )
took 0.10 seconds
>>> time(lambda: dict(flattenDict(makeEvilDict(100000), join=forget)) )
[1] 12569 segmentation fault python
... sigh, don't think that one is my fault...
[unimportant historical note due to moderation issues]
Regarding the alleged duplicate of Flatten a dictionary of dictionaries (2 levels deep) of lists in Python:
That question's solution can be implemented in terms of this one by doing sorted( sum(flatten(...),[]) )
. The reverse is not possible: while it is true that the values of flatten(...)
can be recovered from the alleged duplicate by mapping a higher-order accumulator, one cannot recover the keys. (edit: Also it turns out that the alleged duplicate owner's question is completely different, in that it only deals with dictionaries exactly 2-level deep, though one of the answers on that page gives a general solution.)
System like Ubuntu prefers to use auth_socket plugin. It will try to authenticate by comparing your username in DB and process which makes mysql request; it is described in here
The socket plugin checks whether the socket user name (the operating system user name) matches the MySQL user name specified by the client program to the server, and permits the connection only if the names match.
Instead you may want to back with the mysql_native_password, which will require user/password to authenticate.
About the method to achieve that, I recommend this instead.
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
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
Use String.equalsIgnoreCase()
.
Use the Java API reference to find answers like these:
The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):
import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)
which will produce:
a: [[1 4 0 1]
[1 3 2 4]
[1 0 2 1]
[3 1 0 0]
[1 4 0 1]]
b: [[0 1 0 0]
[0 1 0 1]
[0 0 0 0]
[1 0 0 0]
[0 1 0 0]]
For people looking to do if statements with multiple 'or' values.
<div ng-if="::(a || b || c || d || e || f)"><div>
I've used Sothink SWF decompiler a couple of times, the only problem is that as project gets more complex, the output of decompiler gets harder to compile back again. But it ensures that you can get your .as files most of the time, compilable fla is a question.
Had the same message. I had to remove the Run/Debug configuration.
In my case, I ran the unit test as a local test before. After that I moved my test to the androidTest package and tried to run it again. Android Studio remembered the last run configuration so it tried to run it again as a local unit test which produced the same error.
After removing the config and running the test again it generated a new configuration and worked.
oracleserviceorcl
service. (From services in Task Manager)ORACLE_SID
variable with orcl
value. (In environment variables)Extends FragmentActivity instead of Activity
C99 is available online. Quoted from www.open-std.org:
The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.
You need to create a git repo locally, add your project files to that repo, commit them to the local repo, and then sync that repo to your repo on github. You can find good instructions on how to do the latter bit on github, and the former should be easy to do with the software you've downloaded.
Adding to the top voted answer and many ones above stressing the "more generic, better", I would like to dig a little bit more.
Map
is the structure contract while HashMap
is an implementation providing its own methods to deal with different real problems: how to calculate index, what is the capacity and how to increment it, how to insert, how to keep the index unique, etc.
Let's look into the source code:
In Map
we have the method of containsKey(Object key)
:
boolean containsKey(Object key);
JavaDoc:
boolean java.util.Map.containsValue(Object value)
Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value
v
such that(value==null ? v==null : value.equals(v))
. This operation will probably require time linear in the map size for most implementations of the Map interface.Parameters:value
value whose presence in this map is to betested
Returns:true
if this map maps one or more keys to the specified
valueThrows:
ClassCastException - if the value is of an inappropriate type for this map (optional)
NullPointerException - if the specified value is null and this map does not permit null values (optional)
It requires its implementations to implement it, but the "how to" is at its freedom, only to ensure it returns correct.
In HashMap
:
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
It turns out that HashMap
uses hashcode to test if this map contains the key. So it has the benefit of hash algorithm.
You can not sort TreeMap on values.
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide
comparator
forComparator<? super K>
so your comparator should compare on keys.
To provide sort on values you will need SortedSet. Use
SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1,
Map.Entry<String, Double> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedset.addAll(myMap.entrySet());
To give you an example
SortedMap<String, Double> myMap = new TreeMap<String, Double>();
myMap.put("a", 10.0);
myMap.put("b", 9.0);
myMap.put("c", 11.0);
myMap.put("d", 2.0);
sortedset.addAll(myMap.entrySet());
System.out.println(sortedset);
Output:
[d=2.0, b=9.0, a=10.0, c=11.0]
The direct way of doing this is to create triggers on tables. Set some conditions or mapping methods. When update or delete occurs, it will insert into 'change' table automatically.
But the biggest part is what if we got lots columns and lots of table. We have to type every column's name of every table. Obviously, It's waste of time.
To handle this more gorgeously, we can create some procedures or functions to retrieve name of columns.
We can also use 3rd-part tool simply to do this. Here, I write a java program Mysql Tracker
I had the same problem and got it resolved by deleting .m2 maven repo (C:\Users\user\ .m2)
Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.
I try to give a general rule by using the OPs example
do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"
we have to avoid a branch where $a
gets more than 10, so $a < 10
as a general condition can be applied to every other, following condition.
In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.
So the OPs example with the rule applied may be restructured as:
if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
echo "1"
elif [ "$a" -lt 10 ]
then
echo "2"
fi
Just a variation of the above, enclosing everything in the $a < 10
condition:
if [ "$a" -lt 10 ]
then
if [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
fi
(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)
gem list --no-version | grep -v -e 'psych' -e 'rdoc' -e 'openssl' -e 'json' -e 'io-console' -e 'bigdecimal' | xargs sudo gem uninstall -ax
grep here is excluding default gems. All other gems will be uninstalled. You can also precede it with sudo
in case you get permission issues.
Please check if any jar files missing particularly jars are may have been taken as locally, so put into lib folder then create the WAR file
create table svalue (
name varchar(5),
value int
) engine = myisam;
insert into svalue value ('aaa',30),('bbb',10),('ccc',30),('ddd',20);
select * from svalue where value = (
select value
from svalue
group by value
order by value desc limit 1,1)
Take a look at UrlRewriteFilter which is essentially a java-based implementation of Apache's mod_rewrite.
You'll need to extract it into ROOT
folder under your Tomcat's webapps
folder; you can then configure redirects to any other context within its WEB-INF/urlrewrite.xml
configuration file.
Try using the os
module.
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
See the Python docs on os.environ
. Also, for spawning child processes, see Python's subprocess docs.
You can fix the .
form by using --exclude
:
tar -czf workspace.tar.gz --exclude=workspace.tar.gz .
The most complete, concise definition of false I've come across is:
Anything that stringifies to the empty string or the string
0
is false. Everything else is true.
Therefore, the following values are false:
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to 0
are false, strings that numify to zero aren't necessarily. The only false strings are 0
and the empty string. Any other string, even if it numifies to zero, is true.
The following are strings that are true as a boolean and zero as a number:
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
Scalar::Util::looks_like_number
returns false. (e.g. "abc"
)First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
I found part of the solution. Images now have metadata that specify the orientation of the photo. There is a new CSS spec for image-orientation
.
Just add this to your CSS:
img {
image-orientation: from-image;
}
According to the spec as of Jan 25 2016, Firefox and iOS Safari (behind a prefix) are the only browsers that support this. I'm seeing issues with Safari and Chrome still. However, mobile Safari seems to natively support orientation without the CSS tag.
I suppose we'll have to wait and see if browsers wills start supporting image-orientation
.
Try this tag. This will refresh the index.html
page every 30 seconds.
<meta http-equiv="refresh" content="30;url=index.html">
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
To save your work and exit press Esc and then :wq (w for write and q for quit).
Alternatively, you could both save and exit by pressing Esc and then :x
To set another editor run export EDITOR=myFavoriteEdior
on your terminal, where myFavoriteEdior
can be vi
, gedit
, subl
(for sublime) etc.
BIRT works pretty well.
A list can be sorted and deduplicated using built-in functions:
myList = sorted(set(myList))
I think that using the task scheduler to autostart programs is not very user friendly, and sometimes it has had side effects for me (e.g. tray icon for a program is not added).
To remedy this, I have made a program called Elevated Startup that first relaunches itself with administrator privileges, then it launches all files in a directory. Since Elevated Startup is now elevated, all the programs it then launches is also given administrator privileges. The directory is on the start menu next to the classic Startup directory, and works very much the same.
You may encounter one UAC dialog when the program relaunches itself, depending on your UAC settings.
You can get the program here: https://stefansundin.github.io/elevatedstartup/
The output of ps aux
looks like you did not start docker through systemd/systemctl.
It looks like you started it with:
sudo dockerd -H gridsim1103:2376
When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.
The correct way to start docker is to use systemd/systemctl:
systemctl enable docker
systemctl start docker
After this, docker should start on system start.
EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.
In my case I was passing an object to a promise, within the promise I was adding more key/values to the object and when it was done the promise returned the object.
However, a slight over look on my part, the promise was returning the object before it was fully finished...thus the rest of my code was trying to process the updated object and the data wasn't yet there. But like above, in the console, I saw the object fully updated but wasn't able to access the keys - they were coming back undefined. Until I saw this:
console.log(obj) ;
console.log(obj.newKey1) ;
// returned in console
> Object { origKey1: "blah", origKey2: "blah blah"} [i]
origKey1: "blah"
origKey2: "blah blah"
newKey1: "this info"
newKey2: "that info"
newKey3: " more info"
> *undefined*
The [i] is a little icon, when I hovered over it it said Object value at left was snapshotted when logged, value below was evaluated just now
. Thats when it occurred to me that my object was being evaluated before the promise had fully updated it.
See this article for tips on how to help performance issues. This includes both performance issues related to starting up, under the "cold start" section. Most of this will matter no matter what type of server you are using, locally or in production.
If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services. http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx
If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence=”false” into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list. http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx
http://msdn.microsoft.com/en-us/library/bb629393.aspx
Consider using NGEN on all assemblies. However without careful use this doesn’t give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost. http://msdn.microsoft.com/en-us/magazine/cc163610.aspx
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...
Input one number at a time, and check whether the following character is ,
. If so, discard it.
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "1,2,3,4,5,6";
std::vector<int> vect;
std::stringstream ss(str);
for (int i; ss >> i;) {
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
for (std::size_t i = 0; i < vect.size(); i++)
std::cout << vect[i] << std::endl;
}
Raw t-sql is limited to CHARINDEX(), PATINDEX(), REPLACE(), and SUBSTRING() for string manipulation. But with sql server 2005 and later you can set up user defined functions that run in .Net, which means setting up a string.format() UDF shouldn't be too tough.
define function in .bashrc
function gitall() {
file=${1:-.}
comment=${2:-update}
echo $file
echo $comment
git add $file && git commit -m '$comment' && git push origin master
}
in your terminal
gitall
default gitall will add all in current git repo
gitall some-file-to-add 'update file'
will add certain file to change, and use custom commit message
document.getElementById('iframeID').contentWindow.location.href
You can't access cross-domain iframe location at all.
You can use S3Fs, which is essentially a wrapper around boto3 that exposes typical file-system style operations:
import s3fs
s3 = s3fs.S3FileSystem()
s3.exists('myfile.txt')
As polygenelubricants says yours would look for 0|1-1|2 rather than what you wish for, due to the fact that character classes (things in []) match characters rather than strings.
The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.
You can simply edit your configuration file in a text editor.
In the ~/.gitconfig
you need to put in something like the following:
[user]
name = Uzumaki Naruto
email = [email protected]
[github]
user = myname
token = ff44ff8da195fee471eed6543b53f1ff
In the oldrep/.git/config
file (in the configuration file of your repository):
[remote "github"]
url = [email protected]:myname/oldrep.git
push = +refs/heads/*:refs/heads/*
push = +refs/tags/*:refs/tags/*
If there is a remote section in your repository's configuration file, and the URL matches, you need only to add push configuration. If you use a public URL for fetching, you can put in the URL for pushing as 'pushurl' (warning: this requires the just-released Git version 1.6.4).
assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.
Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"
In the above, I need to extract the "273"
that I will use in database query
//find the length of the string
int streamLen=StreamSelected.Length;
//now remove all characters except the last 10 characters
string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));
//extract the 3 characters using substring starting from index 0
//show Result is a TextBox (txtStreamSubs) with
txtStreamSubs.Text = streamLessTen.Substring(0, 3);
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
Oh, be careful now! All that glitters is NOT gold! All of the “stats” dm views and functions have a problem for this type of thing. They only work against what is in cache and the lifetime of what is in cache can be measure in minutes. If you were to use such a thing to determine which SPs are candidates for being dropped, you could be in for a world of hurt when you delete SPs that were used just minutes ago.
The following excerpts are from Books Online for the given dm views…
sys.dm_exec_procedure_stats Returns aggregate performance statistics for cached stored procedures. The view contains one row per stored procedure, and the lifetime of the row is as long as the stored procedure remains cached. When a stored procedure is removed from the cache, the corresponding row is eliminated from this view.
sys.dm_exec_query_stats The view contains one row per query statement within the cached plan, and the lifetime of the rows are tied to the plan itself. When a plan is removed from the cache, the corresponding rows are eliminated from this view.
If you're using Swift, it's as simple as:
subviews.map { $0.removeFromSuperview }
It's similar in philosophy to the makeObjectsPerformSelector
approach, however with a little more type safety.
An equivalent result, "other things being equal", would be to format all cells grey and then use Go To Special to select the blank cells prior to removing their grey highlighting.
The problem occurs in declaring context, while using Glide for ImageView or While using intent in recyclerview for item onClick. I Found this working for me which helps me to Declare context to use in Glide or Intent or Toast.
public class NoteAdapter extends FirestoreRecyclerAdapter<Note,NoteAdapter.NoteHolder> {
Context context;
public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull NoteHolder holder, int position, @NonNull Note model) {
holder.r_tv.setText(model.getTitle());
Glide.with(CategoryActivity.context).load(model.getImage()).into(holder.r_iv);
context = holder.itemView.getContext();
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(context, SuggestActivity.class);
context.startActivity(i);
}
});
}
@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category,parent,false);
return new NoteHolder(v);
}
public static class NoteHolder extends RecyclerView.ViewHolder
{
TextView r_tv;
ImageView r_iv;
public NoteHolder(@NonNull View itemView) {
super(itemView);
r_tv = itemView.findViewById(R.id.r_tv);
r_iv = itemView.findViewById(R.id.r_iv);
}
}
}
As a follow-up:
The previous code shown in this post was eventually abandoned because it was unreliable. I am now using the following API function to resize the grid, as recommended by the jqGrid documentation:
jQuery("#targetGrid").setGridWidth(width);
To do the actual resizing, a function implementing the following logic is bound to the window's resize event:
Calculate the width of the grid using its parent's clientWidth and (if that is not available) its offsetWidth attribute.
Perform a sanity check to make sure width has changed more than x pixels (to work around some application-specific problems)
Finally, use setGridWidth() to change the grid's width
Here is example code to handle resizing:
jQuery(window).bind('resize', function() {
// Get width of parent container
var width = jQuery(targetContainer).attr('clientWidth');
if (width == null || width < 1){
// For IE, revert to offsetWidth if necessary
width = jQuery(targetContainer).attr('offsetWidth');
}
width = width - 2; // Fudge factor to prevent horizontal scrollbars
if (width > 0 &&
// Only resize if new width exceeds a minimal threshold
// Fixes IE issue with in-place resizing when mousing-over frame bars
Math.abs(width - jQuery(targetGrid).width()) > 5)
{
jQuery(targetGrid).setGridWidth(width);
}
}).trigger('resize');
And example markup:
<div id="grid_container">
<table id="grid"></table>
<div id="grid_pgr"></div>
</div>
More info about why it wasn't working for me in case it helps future people:
The reason why it wasn't working is that {% include %} in django doesn't like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters and then it included successfully.
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row
UPDATE table_name
SET new_pk_column = sequence_name.nextval;
Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)
ALTER TABLE table_name
ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )
If you want to generate the key automatically, you'd need to add a trigger
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
:new.new_pk_column := sequence_name.nextval;
END;
If you are on an older version of Oracle, the syntax is a bit more cumbersome
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
SELECT sequence_name.nextval
INTO :new.new_pk_column
FROM dual;
END;
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
x = getattr(self, source)
will work just perfectly if source
names ANY attribute of self, including the other_data
in your example.
I solved this problem with:
inputObj.css('cssText', inputObj.attr('style')+'padding-left: ' + (width + 5) + 'px !IMPORTANT;');
So no inline-Style is lost, an the last overrides the first
What you probably need to do is redirect the user after the POST / Form Handler script has been ran.
In PHP this is done like so...
<?php
// ... Handle $_POST data, maybe insert it into a database.
// Ok, $_POST data has been handled, redirect the user
header('Location:success.php');
die();
?>
... this should allow you to refresh the page without getting that "Send Data Again" warning.
You can even redirect to the same page (if that's what you're posting to) as the POST variables will not be sent in the headers (and thus not be there to re-POST on refresh)
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
Heres a simple solution in Swift 5/iOS 13.
extension Date {
func toMilliseconds() -> Int64 {
Int64(self.timeIntervalSince1970 * 1000)
}
init(milliseconds:Int) {
self = Date().advanced(by: TimeInterval(integerLiteral: Int64(milliseconds / 1000)))
}
}
This however assumes you have calculated the difference between UTF time and local time and adjusted and accounted for in the milliseconds. For that look to calendar
var cal = Calendar.current
cal.timeZone = TimeZone(abbreviation: "UTC")!
let difference = cal.compare(dateGiven, to: date, toGranularity: .nanosecond)
I think you are talking about padding strings with spaces.
One way to do this is with string format codes.
For example, if you want to pad a string to a certain length with spaces, use something like this:
String padded = String.format("%-20s", str);
In a formatter, %
introduces a format sequence. The -
means that the string will be left-justified (spaces will be added on the right of the string). The 20
means the resulting string will be 20 characters long. The s
is the character string format code, and ends the format sequence.