git ls-tree --full-tree -r HEAD
and git ls-files
return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]
. For example:
git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64 glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841 glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35 glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0 glyphicons-halflings-regular.woff2
In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97
is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>...
of course.
In your controller class, just add @ComponentScan("package") annotation. In my case the package name is com.shoppingcart.So i wrote the code as @ComponentScan("com.shoppingcart") and it worked for me.
If you are more interested in measuring semantic similarity of two pieces of text, I suggest take a look at this gitlab project. You can run it as a server, there is also a pre-built model which you can use easily to measure the similarity of two pieces of text; even though it is mostly trained for measuring the similarity of two sentences, you can still use it in your case.It is written in java but you can run it as a RESTful service.
Another option also is DKPro Similarity which is a library with various algorithm to measure the similarity of texts. However, it is also written in java.
code example:
// this similarity measure is defined in the dkpro.similarity.algorithms.lexical-asl package
// you need to add that to your .pom to make that example work
// there are some examples that should work out of the box in dkpro.similarity.example-gpl
TextSimilarityMeasure measure = new WordNGramJaccardMeasure(3); // Use word trigrams
String[] tokens1 = "This is a short example text .".split(" ");
String[] tokens2 = "A short example text could look like that .".split(" ");
double score = measure.getSimilarity(tokens1, tokens2);
System.out.println("Similarity: " + score);
u can rename the class as classA.mm and add C++ features in it.
it will create the file in the root directory of your project/solution.
You can specify a location of choice in the web.config of your app as follows:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:/ServiceLogs/Olympus.Core.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value=".yyyyMMdd.log" />
<maximumFileSize value="5MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
<maxSizeRollBackups value="-1" />
<countDirection value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
</layout>
</appender>
the file tag specifies the location.
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
If you can use apache.commons.lang in your project, the easiest way would be just to use the method provided there:
public static boolean containsWhitespace(CharSequence seq)
Check whether the given CharSequence contains any whitespace characters.
Parameters:
seq - the CharSequence to check (may be null)
Returns:
true if the CharSequence is not empty and contains at least 1 whitespace character
It handles empty and null parameters and provides the functionality at a central place.
Enable less secure apps on your gmail account and use (Python>=3.6):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
gmailUser = '[email protected]'
gmailPassword = 'XXXXX'
recipient = '[email protected]'
message = f"""
Type your message here...
"""
msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Subject here..."
msg.attach(MIMEText(message))
try:
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print ('Email sent!')
except:
print ('Something went wrong...')
concat.js is being included in the concat
task's source files public/js/*.js
. You could have a task that removes concat.js
(if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.
If doing the latter, you could put all your sources under ./src
and your built files under ./dest
src
+-- css
¦ +-- 1.css
¦ +-- 2.css
¦ +-- 3.css
+-- js
+-- 1.js
+-- 2.js
+-- 3.js
Then set up your concat task
concat: {
js: {
src: 'src/js/*.js',
dest: 'dest/js/concat.js'
},
css: {
src: 'src/css/*.css',
dest: 'dest/css/concat.css'
}
},
Your min task
min: {
js: {
src: 'dest/js/concat.js',
dest: 'dest/js/concat.min.js'
}
},
The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file
grunt.loadNpmTasks('grunt-css');
And then set it up
cssmin: {
css:{
src: 'dest/css/concat.css',
dest: 'dest/css/concat.min.css'
}
}
Notice that the usage is similar to the built-in min.
Change your default
task to
grunt.registerTask('default', 'concat min cssmin');
Now, running grunt
will produce the results you want.
dest
+-- css
¦ +-- concat.css
¦ +-- concat.min.css
+-- js
+-- concat.js
+-- concat.min.js
Now there is already no need to use JSON.stringify
explicitly. Just execute this line of code
$.cookie.json = true;
After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.
var user = { name: "name", age: 25 }
$.cookie('user', user);
...
var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);
But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js
The simplest, and best long-term solution
Go to the main menu on top of Eclipse and locate Window next to Run and expand it.
Window->Reset Perspective... to restore all views to their defaults
It will reset the default setting.
Template literals
may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.
I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literals
are. Please read about Template literals here.
var a = 1, b = 2;_x000D_
var div = document.createElement('div');_x000D_
div.setAttribute('class', 'post block bc2');_x000D_
div.innerHTML = `_x000D_
<div class="parent">_x000D_
<div class="child">${a}</div>_x000D_
<div class="child">+</div>_x000D_
<div class="child">${b}</div>_x000D_
<div class="child">=</div>_x000D_
<div class="child">${a + b}</div>_x000D_
</div>_x000D_
`;_x000D_
document.getElementById('posts').appendChild(div);
_x000D_
.parent {_x000D_
background-color: blue;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
.post div {_x000D_
color: white;_x000D_
font-size: 2.5em;_x000D_
padding: 20px;_x000D_
}
_x000D_
<div id="posts"></div>
_x000D_
You could use width: 100%;
in your css.
Answer seems to be a little old, What I did was to use this mapper to convert a MAP
ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);
a simple Map
:
Map<String, Object> user = new HashMap<String,Object>(); user.put( "id", teklif.getAccount().getId() ); user.put( "fname", teklif.getAccount().getFname()); user.put( "lname", teklif.getAccount().getLname()); user.put( "email", teklif.getAccount().getEmail()); user.put( "test", null);
Use it like this for example:
String json = mapper.writeValueAsString(user);
I want to delete my sqlite db from document directory.I delete the sqlite db successfully by below answer
NSString *strFileName = @"sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
NSLog(@"The file name is - %@",[filename pathExtension]);
if ([[filename pathExtension] isEqualToString:strFileName]) {
[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
NSLog(@"The sqlite is deleted successfully");
}
}
You can remove class active
from all .tab
and use $(this)
to target current clicked .tab
:
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
$(this).addClass("active");
});
});
Your code won't work because after removing class active
from all .tab
, you also add class active
to all .tab
again. So you need to use $(this)
instead of $('.tab')
to add the class active
only to the clicked .tab
anchor
I would do
import os
path = os.path.normpath(path)
path.split(os.sep)
First normalize the path string into a proper string for the OS. Then os.sep
must be safe to use as a delimiter in string function split.
With VS 2015 and up, Use the Smart Command Line Arguments extension. This plug-in adds a window that allows you to turn arguments on and off:
The extension additionally stores the arguments in a JSON file, allowing you to commit them to source control. In addition to ensuring you don't have to type in all the arguments every single time, this serves as a useful supplement to your documentation for other developers to discover the available options.
Replace bigint(20) not null auto_increment
by bigserial not null
and
datetime
by timestamp
JPanel jPanel = new JPanel();
jPanel.setBorder(BorderFactory.createLineBorder(Color.black));
Here not only jPanel, you can add border to any Jcomponent
Try providing the proxy details as parameters
sbt compile -Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port
If that is not working then try with JAVA_OPTS (non windows)
export JAVA_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"
sbt compile
or (windows)
set JAVA_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"
sbt compile
if nothing works then set SBT_OPTS
(non windows)
export SBT_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"'
sbt compile
or (windows)
set SBT_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=port -Dhttp.proxyHost=localhost -Dhttp.proxyPort=port"
sbt compile
I usually do it using add_all
.
from app import session
from models import User
objects = [User(name="u1"), User(name="u2"), User(name="u3")]
session.add_all(objects)
session.commit()
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});
This is how I usually do it. A simple number of days perspective of B minus A.
DATE_PART('day', MAX(joindate) - MIN(joindate)) as date_diff
Durgesh's approach does work.
I also used such KVC solutions many times. Despite it seems to be undocumented, but it works. Frankly, you don't use any private methods here - only Key-Value Coding which is legal.
P.S. Yesterday my new app appeared at AppStore without any problems with this approach. And it is not the first case when I use KVC in changing some read-only properties (like navigatonBar) or private ivars.
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
DECLARE @CarList nvarchar(max);
SET @CarList = N'';
SELECT @CarList+=CarName+N','
FROM dbo.CARS;
SELECT LEFT(@CarList,LEN(@CarList)-1);
Thanks are due to whoever on SO showed me the use of accumulating data during a query.
If you want to avoid parsing the date and just want a timestamp in GMT, you could use:
final Date gmt = new Timestamp(System.currentTimeMillis()
- Calendar.getInstance().getTimeZone()
.getOffset(System.currentTimeMillis()));
You set the style per element and not by its content:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML
you get/set the content of an element. So if you would want to modify your title, innerHTML
would be the way to go.
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style
property of the element itself.
This situation occured if there are object in repository, which creates by current transaction.
Simple scenario:
Same thing when adding same files from two working copies.
My personal fav PrettyC wantabe is uncrustify: http://uncrustify.sourceforge.net/. It's got a few billion options however so I also suggest you download UniversalIndentGUI_macx, (also on sourceforge) a GUI someone wrote to help set the options the way you like them.
You can then add this custom user script to uncrustify the selected text:
#! /bin/sh
#
# uncrustify!
echo -n "%%%{PBXSelection}%%%"
/usr/local/bin/uncrustify -q -c /usr/local/share/uncrustify/geo_uncrustify.cfg -l oc+ <&0
echo -n "%%%{PBXSelection}%%%"
What about using the a
option?
According to the docs:
'a+' - Open file for reading and appending. The file is created if it does not exist.
It seems to work perfectly with createWriteStream
The most common solution is to strip the integer portion of the number and compare it to zero like so:
function Test()
{
var startVal = 123.456
alert( (startVal - Math.floor(startVal)) != 0 )
}
Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:
<activity android:name=".SomeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
You can have a map injected using @ConfigurationProperties
:
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
public class MapBindingSample {
public static void main(String[] args) throws Exception {
System.out.println(SpringApplication.run(MapBindingSample.class, args)
.getBean(Test.class).getInfo());
}
@Bean
@ConfigurationProperties
public Test test() {
return new Test();
}
public static class Test {
private Map<String, Object> info = new HashMap<String, Object>();
public Map<String, Object> getInfo() {
return this.info;
}
}
}
Running this with the yaml in the question produces:
{build={artifact=${project.artifactId}, version=${project.version}, name=${project.name}, description=${project.description}}}
There are various options for setting a prefix, controlling how missing properties are handled, etc. See the javadoc for more information.
You must build an executable file before you can run it. So if you don't “BUILD” your file, then it will not be able to link and load that object file, and hence it does not have the required binary numbers to execute.
So basically right click on the Project -> Build Project -> Run As Local C/C++ Application
should do the trick
Methods Where authenticity_token
is required
authenticity_token
is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.
Why It is Required
It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with
authenticity_token
stored in session. Ifauthenticity_token
is same then process is continue otherwise it does not perform actions.
Note that Math.hypot
is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.
So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1)
.
Try figsize
param in df.plot(figsize=(width,height))
:
df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));
df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));
The size in figsize=(5,3)
is given in inches
per (width, height)
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html
You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.
If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.
A simple example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());
I hit this message as well. In my case, I didn't want to keep the files, so this worked for me:
git clean -d -f .
git clean -d -f ""
If you also want to remove files ignored by git, then execute the following command.
git clean -d -fx .
git clean -d -fx ""
http://www.kernel.org/pub/software/scm/git/docs/git-clean.html
-x
means ignored files are also removed as well as files unknown to git.
-d
means remove untracked directories in addition to untracked files.
-f
is required to force it to run.
private final String easyPuzzle ="630208010200050089109060030"+
"008006050000187000060500900"+
"09007010681002000502003097";
Bundle ePzl= new Bundle();
ePzl.putString("key", easyPuzzle);
Intent i = new Intent(MainActivity.this,AnotherActivity.class);
i.putExtras(ePzl);
startActivity(i);
Now go to AnotherActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_activity);
Bundle p = getIntent().getExtras();
String yourPreviousPzl =p.getString("key");
}
now "yourPreviousPzl" is your desired string.
This expression 12-4-2005
is a calculated int and the value is -1997
. You should do like this instead '2005-04-12'
with the '
before and after.
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
Got an answer for this problem without using ExifInterface. We can get the rotation of the camera either front camera or back camera whichever you are using then while creating the Bitmap we can rotate the bitmap using Matrix.postRotate(degree)
public int getRotationDegree() {
int degree = 0;
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
degree = info.orientation;
return degree;
}
}
return degree;
}
After calculating the rotation you can rotate you bitmap like below:
Matrix matrix = new Matrix();
matrix.postRotate(getRotationDegree());
Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
Herare bm should be your bitmap.
If you want to know the rotation of your front camera just change Camera.CameraInfo.CAMERA_FACING_BACK to Camera.CameraInfo.CAMERA_FACING_FRONT above.
I hope this helps.
In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation
The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE)
where each window is related to image container by the name arg, make sure to use same name
eg:
import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)
library(purrr)
x <- x %>% keep(is.numeric)
Map.Entry
is a key and its value combined into one class. This allows you to iterate over Map.entrySet()
instead of having to iterate over Map.keySet()
, then getting the value for each key. A better way to write what you have is:
for (Map.Entry<String, JButton> entry : listbouton.entrySet())
{
String key = entry.getKey();
JButton value = entry.getValue();
this.add(value);
}
If this wasn't clear let me know and I'll amend my answer.
You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).
table {
background: #fff;
box-shadow: 0 0 0 10px #fff;
margin: 10px;
width: calc(100% - 20px);
}
all above fix may not work in android studio .if you are using ANDROID STUDIO...... use this fix
add
xmlns:compat="http://schemas.android.com/tools"
in menu tag instead of
xmlns:compat="http://schemas.android.com/apk/res-auto"
in menu tag.
just use this to replace all white spaces with
-
:
myString.replace(/ /g,"-")
None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden
?". Neither :visible
nor :hidden
will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});
You usually want to use NSInteger
when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible integer type, which on 32 bit systems is just an int
, while on a 64-bit system it's a long
.
I'd stick with using NSInteger
instead of int
/long
unless you specifically require them.
NSInteger
/NSUInteger
are defined as *dynamic typedef
*s to one of these types, and they are defined like this:
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
With regard to the correct format specifier you should use for each of these types, see the String Programming Guide's section on Platform Dependencies
You can use default.
public void OptionalParameters(int requerid, int optinal = default){}
Your live apps will not be taken down. Nothing will happen to anything that is live in the app store.
Once they formally expire, the only thing that will be impacted is your ability to sign code (and thus make new builds and provide updates).
Regarding your distribution certificate, once it expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. If you want to renew it before it expires, revoke the current certificate and you will get a button to request a new one.
Regarding the provisioning profile, don't worry about it before expiration, just keep using it. It's easy enough to just renew it once it expires.
The peace of mind is that nothing will happen to your live app in the store.
You can specify a callback function:
$(selector).fadeOut('slow', function() {
// will be called when the element finishes fading out
// if selector matches multiple elements it will be called once for each
});
usually in maven we have two types of builds 1)Snapshot builds 2)Release builds
snapshot builds:SNAPSHOT is the special version that indicate current deployment copy not like a regular version, maven checks the version for every build in the remote repository so the snapshot builds are nothing but development builds.
Release builds:Release means removing the SNAPSHOT at the version for the build, these are the regular build versions.
For QT 5
Step1:
.pro
(in pro file, add these 2 lines)
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
Step2:
In main.cpp
replace code:
#include <QtGui/QApplication>
with:
#include <QApplication>
Python suggests users use len()
instead of __len__()
for consistency, just like other guys said. However, There're some other benefits:
For some built-in types like list
, str
, bytearray
and so on, the Cython implementation of len()
takes a shortcut. It directly returns the ob_size
in a C structure, which is faster than calling __len__()
.
If you are interested in such details, you could read the book called "Fluent Python" by Luciano Ramalho. There're many interesting details in it, and may help you understand Python more deeply.
If you want it to be truly dynamic and select the radio that corresponds to the incoming data, this works. It's using the gender value of the data passed in or uses default.
if(data['gender'] == ''){
$('input:radio[name="gender"][value="Male"]').prop('checked', true);
}else{
$('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
};
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
Just to update these answers, ESRI has included this tool, known as Layer to KML in ArcMap 10.X. Also, a Map to KML tool exists.
Simply import the desired layer (vector or raster) and choose the output location, resolution, etc. Very simple tool.
One way is to loop through the keys of the dictionary, which I recommend:
foreach(int key in sp.Keys)
dynamic value = sp[key];
Another way, is to loop through the dictionary as a sequence of pairs:
foreach(KeyValuePair<int, dynamic> pair in sp)
{
int key = pair.Key;
dynamic value = pair.Value;
}
I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys
property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x)
helps you retrieve the items in ascending order of the key. Note that Dictionary
uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.
Update (01 Dec 2016): replaced var
s with actual types to make the answer more clear.
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
You can implement it in your ViewDidLoad
Method:
continuebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 100, view1.frame.size.width-20, 40)];
[continuebtn setBackgroundColor:[UIColor grayColor]];
[continuebtn setTitle:@"Continue" forState:UIControlStateNormal];
continuebtn.layer.cornerRadius = 10;
continuebtn.layer.borderWidth =1.0;
continuebtn.layer.borderColor = [UIColor blackColor].CGColor;
[continuebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[continuebtn addTarget:self action:@selector(continuetonext) forControlEvents:UIControlEventTouchUpInside];
[view1 addSubview:continuebtn];
Where continuetonext
is:
-(void)continuetonext
{
GeneratePasswordVC *u = [[GeneratePasswordVC alloc]init];
[self.navigationController pushViewController:u animated:YES];
}
First of all my Search query value is from a user's input. I have tried all the answers on this one and all the results Google have given me, 90% of the answers says put '%''%' and the other 10% says a more complicated answers.
For some reason all of those did not work for me.
How ever I remembered that in MySQL (phpmyadmin) there is this built in search function so I tried it just to see how MySQL handles a search with an apostrophe, turns out MySQL just escaping apostrophe with a backslash LIKE '%\'%'
so why just I replace apostrophe with a \'
in every user's query.
This is what I come up with:
if(!empty($user_search)) {
$r_user_search = str_ireplace("'","\'","$user_search");
$find_it = "SELECT * FROM table WHERE column LIKE '%$r_user_search%'";
$results = $pdo->prepare($find_it);
$results->execute();
This solves my problem. Also please correct me if this is still has security issues.
with SAP, you might be referring to a popular business software:
http://en.wikipedia.org/wiki/SAP_AG
And according to Wikipedia, ABAP is a programming language (short for Advanced Business Application Programming) created by SAP AG.
I spent ages trying to fix this. Every solution talks about 'setting options'. I don't know what that means. Finally, I figured it out. You can just include a commented out line at the top of the file /*jshint esversion: 6 */
.
USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL
DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL
DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition
SELECT id FROM t6;
--IDs empty.
SELECT id FROM t7;
--ID is empty.
--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/
SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the
INSERT statement two statements before this query.*/
SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/
SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/
-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action
up to this point in this session.*/
SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action
up to this point in this scope in this session.*/
SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/
An ellipsis is three periods in a row...
The TextView will use an ellipsis when it cannot expand to show all of its text. The attribute ellipsized
sets the position of the three dots if it is necessary.
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
As far as I remember the standard, all function declarations are considered as "extern" by default, so there is no need to specify it explicitly.
That doesn't make this keyword useless since it can also be used with variables (and it that case - it's the only solution to solve linkage problems). But with the functions - yes, it's optional.
Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.
In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.
To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.
Why?
It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.
See the following information in MSDN about the GAC changes in 4.0.
For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.
As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.
i was looking for the same and found the answer,
solution is to use the styled map, on below link you can create your custom styles through wizard and test is at the same time google map style wizard
you can check all available options : here
here is my sample code which creates boundary for states and hide all the road and there labels.
var styles = [
{
"featureType": "administrative.province",
"elementType": "geometry.stroke",
"stylers": [
{ "visibility": "on" },
{ "weight": 2.5 },
{ "color": "#24b0e2" }
]
},{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "administrative.locality",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "road",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': "rajasthan"
}, (results, status)=> {
var mapOpts = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
scrollwheel: false,
styles:styles,
center: results[0].geometry.location,
zoom:6
}
map = new google.maps.Map(document.getElementById("map"), mapOpts);
});
While making image with fully transparent background in PNG-8, the outline of the image looks prominent with little white bits. But in PNG-24 the outline is gone and looks perfect. Transparency in PNG-24 is greater and cleaner than PNG-8.
PNG-8 contains 256 colors, while PNG-24 contains 16 million colors.
File size is almost double in PNG-24 than PNG-8.
use the HorizontalContentAlignment property.
Sample
<Label HorizontalContentAlignment="Center"/>
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.
if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.
Normally SDB will download the driver in the **android-sdk-windows\extras\google\usb_driver** path
Here are the steps that worked for me:
And hopefully, it will work.
In the specific case of the code example from the original question, the
System.out.print("\n");
is there to move to a new line between incrementing i.
So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.
You can put a ^
in the beginning of a character set to match anything but those characters.
[^=]*
will match everything but =
A full answer: (Tested with r71)
To set a background color use:
renderer.setClearColor( 0xffffff ); // white background - replace ffffff with any hex color
If you want a transparent background you will have to enable alpha in your renderer first:
renderer = new THREE.WebGLRenderer( { alpha: true } ); // init like this
renderer.setClearColor( 0xffffff, 0 ); // second param is opacity, 0 => transparent
View the docs for more info.
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
you can't do multiple inheritance in java. consider using interfaces:
interface I1 {}
interface I2 {}
class C implements I1, I2 {}
or inner classes:
class Outer {
class Inner1 extends Class1 {}
class Inner2 extends Class2 {}
}
By using this you can get the text, value and data attribute.
<select name="your_name" id="your_id" onchange="getSelectedDataAttribute(this)">
<option value="1" data-id="123">One</option>
<option value="2" data-id="234">Two</option>
</select>
function getSelectedDataAttribute(event) {
var selected_text = event.options[event.selectedIndex].innerHTML;
var selected_value = event.value;
var data-id = event.options[event.selectedIndex].dataset.id);
}
you need to do something like this,
SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus.*2100';
or
SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus)+.*(2100)+';
Create a new table called comments
They should have a column containing the id of the post they are assigned to.
Make a form which adds a new comment to that table.
An example (not tested so may contain lil' syntax errors): I call a page with comments a post
Post.php
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<?php
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<p>
<?php echo;$row->body; ?>
</p>
</div>
<?php
}
?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />
</form>
insertcomment.php
<?php
//First check if everything is filled in
if(/*some statements*/)
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)
You need to set a border-right
on the td's then target the last tds in a row to set the border to none
. Ways to target:
td
of each row and use thattd + td + td
td:last-child
lint is a tool that is used to mark the source code with some suspicious and non-structural (may cause bug). It is a static code analysis tool in C at the beginning.Now it became the generic term used to describe the software analysis tool that mark the suspicious code.
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
Either use:
$("#datetimepicker1").data("datetimepicker").getDate();
Or (from looking at the page source):
$("#datetimepicker1").find("input").val();
The returned value will be a Date
(for the first example above), so you need to format it yourself:
var date = $("#datetimepicker1").data("datetimepicker").getDate(),
formatted = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours + ":" + date.getMinutes() + ":" + date.getSeconds();
alert(formatted);
Also, you could just set the format as an attribute:
<div id="datetimepicker1" class="date">
<input data-format="yyyy-MM-dd hh:mm:ss" type="text"></input>
</div>
and you could use the $("#datetimepicker1").find("input").val();
The problem is in the font-weight
.
For Font Awesome 5
you have to use {font-weight:900}
//Hope This will help you..
DataTable table = new DataTable();
//DataRow[] rowArray = dataTable.Select();
table = dataTable.Clone();
for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
{
table.ImportRow(dataTable.Rows[i]);
}
return table;
please check the jquery mobile scrollstop event
$(document).on("scrollstop",function(){
alert("Stopped scrolling!");
});
I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.
i applied the above solution and can convert my data to SQL.
System.IO.Path.GetTempPath()
is just a wrapper for a native call to GetTempPath(..)
in Kernel32.
Have a look at http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx
Copied from that page:
The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:
- The path specified by the TMP environment variable.
- The path specified by the TEMP environment variable.
- The path specified by the USERPROFILE environment variable.
- The Windows directory.
It's not entirely clear to me whether "The Windows directory" means the temp directory under windows or the windows directory itself. Dumping temp files in the windows directory itself sounds like an undesirable case, but who knows.
So combining that page with your post I would guess that either one of the TMP, TEMP or USERPROFILE variables for your Administrator user points to the windows path, or else they're not set and it's taking a fallback to the windows temp path.
In a comment on @paxdiablo's answer, you asked:
"So basically, is it better to use Double than Float?"
That is a complicated question. I will deal with it in two parts
double
versus float
On the one hand, a double
occupies 8 bytes versus 4 bytes for a float
. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double
values is typically slower than with float
values ... though once again this is hardware dependent.
On the other hand, a double
can represent larger (and smaller) numbers than a float
and can represent them with more than twice the precision. For the details, refer to Wikipedia.
The tricky question is knowing whether you actually need the extra range and precision of a double
. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double
is going to give you enough precision. (And beware of the trap of expecting float
and double
to give you an exact representation. They won't and they can't!)
There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.
Double
versus Float
For the Double
versus Float
case, the issues of precision and range are the same as for double
versus float
, but the relative performance measures will be slightly different.
A Double
(on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float
. Compare this to 8 bytes versus 4 bytes for the double
versus float
case. So the ratio is 5 to 4 versus 2 to 1.
Arithmetic involving Double
and Float
typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double
case.
Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double
in preference to float
, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float
will make a difference with respect to that requirement.
SQL Server does not have literal true or false values. You'll need to use the 1=1
method (or similar) in the rare cases this is needed.
One option is to create your own named variables for true and false
DECLARE @TRUE bit
DECLARE @FALSE bit
SET @TRUE = 1
SET @FALSE = 0
select * from SomeTable where @TRUE = @TRUE
But these will only exist within the scope of the batch (you'll have to redeclare them in every batch in which you want to use them)
Array is a JavaScript native object, why don't you just try to use the API of it? Knowing API on its own will save you time when you will switch to pure JavaScript or another framework.
There are number of different possibilities, so, use the one which mostly targets your needs.
Creating array with values:
var array = ["value1", "value2", "value3"];
Adding values to the end
var array = [];
array.push("value1");
array.push("value2");
array.push("value3");
Adding values to the begin:
var array = [];
array.unshift("value1");
array.unshift("value2");
array.unshift("value3");
Adding values at some index:
var array = [];
array[index] = "value1";
or by using splice
array.splice(index, 0, "value1", "value2", "value3");
Choose one you need.
Here is a site with a clear explanation and graphical illustration of using git merge --no-ff
:
Until I saw this, I was completely lost with git. Using --no-ff
allows someone reviewing history to clearly see the branch you checked out to work on. (that link points to github's "network" visualization tool) And here is another great reference with illustrations. This reference complements the first one nicely with more of a focus on those less acquainted with git.
If you are like me, and not a Git-guru, my answer here describes handling the deletion of files from git's tracking without deleting them from the local filesystem, which seems poorly documented but often occurrence. Another newb situation is getting current code, which still manages to elude me.
I updated a package to my website and had to go back to my notes to see my workflow; I thought it useful to add an example to this answer.
My workflow of git commands:
git checkout -b contact-form
(do your work on "contact-form")
git status
git commit -am "updated form in contact module"
git checkout master
git merge --no-ff contact-form
git branch -d contact-form
git push origin master
Below: actual usage, including explanations.
Note: the output below is snipped; git is quite verbose.
$ git status
# On branch master
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: ecc/Desktop.php
# modified: ecc/Mobile.php
# deleted: ecc/ecc-config.php
# modified: ecc/readme.txt
# modified: ecc/test.php
# deleted: passthru-adapter.igs
# deleted: shop/mickey/index.php
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# ecc/upgrade.php
# ecc/webgility-config.php
# ecc/webgility-config.php.bak
# ecc/webgility-magento.php
Notice 3 things from above:
1) In the output you can see the changes from the ECC package's upgrade, including the addition of new files.
2) Also notice there are two files (not in the /ecc
folder) I deleted independent of this change. Instead of confusing those file deletions with ecc
, I'll make a different cleanup
branch later to reflect those files' deletion.
3) I didn't follow my workflow! I forgot about git while I was trying to get ecc working again.
Below: rather than do the all-inclusive git commit -am "updated ecc package"
I normally would, I only wanted to add the files in the /ecc
folder. Those deleted files weren't specifically part of my git add
, but because they already were tracked in git, I need to remove them from this branch's commit:
$ git checkout -b ecc
$ git add ecc/*
$ git reset HEAD passthru-adapter.igs
$ git reset HEAD shop/mickey/index.php
Unstaged changes after reset:
M passthru-adapter.igs
M shop/mickey/index.php
$ git commit -m "Webgility ecc desktop connector files; integrates with Quickbooks"
$ git checkout master
D passthru-adapter.igs
D shop/mickey/index.php
Switched to branch 'master'
$ git merge --no-ff ecc
$ git branch -d ecc
Deleted branch ecc (was 98269a2).
$ git push origin master
Counting objects: 22, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 59.00 KiB, done.
Total 14 (delta 10), reused 0 (delta 0)
To [email protected]:me/mywebsite.git
8a0d9ec..333eff5 master -> master
Having used this process 10+ times in a day, I have taken to writing batch scripts to execute the commands, so I made an almost-proper git_update.sh <branch> <"commit message">
script for doing the above steps. Here is the Gist source for that script.
Instead of git commit -am
I am selecting files from the "modified" list produced via git status
and then pasting those in this script. This came about because I made dozens of edits but wanted varied branch names to help group the changes.
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
After reading all the answers here - how to summarize grouped information, i decided to skip it all and just loaded one of the SQL javascript libraries. I'm using alasql, yeah it takes a few secs longer on load time but saves countless time in coding and debugging, Now to group and sum() I just use,
$scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);
I know this sounds like a bit of a rant on angular/js but really SQL solved this 30+ years ago and we shouldn't have to re-invent it within a browser.
I install the Oracle server and it allows to connect from the local machine with no problem. But from another Maclaptop on my home network, it can't connect using either Sql Developer or Sql Plus. After doing some research, I figured out there is this additional step you have to do:
Use the Oracle net manager. Select the Listener. Add the IP address (in my case it is 192.168.1.12) besides of the 127.0.0.1 or localhost.
This will end up add an entry to the [OracleHome]\product\11.2.0\dbhome_1\network\admin\listener.ora
restart the listener service. (note: for me I reboot machine once to make it work)
Use lsnrctl status to verify
Notice the additional HOST=192.168.1.12 shows up and this is what to make remote connection to work.
C:\Windows\System32>lsnrctl status
LSNRCTL for 64-bit Windows: Version 11.2.0.1.0 - Production on 05-SEP-2015 13:51:43
Copyright (c) 1991, 2010, Oracle. All rights reserved.
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
Alias LISTENER
Version TNSLSNR for 64-bit Windows: Version 11.2.0.1.0 - Production
Start Date 05-SEP-2015 13:45:18
Uptime 0 days 0 hr. 6 min. 24 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
D:\oracle11gr2\product\11.2.0\dbhome_1\network\admin\listener.ora
Listener Log File d:\oracle11gr2\diag\tnslsnr\eagleii\listener\alert\log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\.\pipe\EXTPROC1521ipc)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.12)(PORT=1521)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "xe" has 1 instance(s).
Instance "xe", status READY, has 1 handler(s) for this service... Service "xeXDB" has 1 instance(s).
Instance "xe", status READY, has 1 handler(s) for this service... The command completed successfully
use tnsping to test the connection
ping the IPv4 address, not the localhost or the 127.0.0.1
C:\Windows\System32>tnsping 192.168.1.12
TNS Ping Utility for 64-bit Windows: Version 11.2.0.1.0 - Production on 05-SEP-2015 14:09:11
Copyright (c) 1997, 2010, Oracle. All rights reserved.
Used parameter files:
D:\oracle11gr2\product\11.2.0\dbhome_1\network\admin\sqlnet.oraUsed EZCONNECT adapter to resolve the alias
Attempting to contact (DESCRIPTION=(CONNECT_DATA=(SERVICE_NAME=))(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.12)(PORT=1521)))
OK (0 msec)
If you don't know the width of the element you can use this code:
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
Demo at fiddle: http://jsfiddle.net/wrh7a21r/
When I just run this as a page
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;
it works fine.
What version of PHP are you running?
Could you try echoing something else after: $testObject->split_for_sms($Chat);
Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.
Hope you get a bit further with this.
This question may be old, but it deserves an update. Here is another way to do that:
#yourdiv {
display: flex;
width:100%;
height:100%;
}
My way of doing it:
from time import time
def printTime(start):
end = time()
duration = end - start
if duration < 60:
return "used: " + str(round(duration, 2)) + "s."
else:
mins = int(duration / 60)
secs = round(duration % 60, 2)
if mins < 60:
return "used: " + str(mins) + "m " + str(secs) + "s."
else:
hours = int(duration / 3600)
mins = mins % 60
return "used: " + str(hours) + "h " + str(mins) + "m " + str(secs) + "s."
Set a variable as start = time()
before execute the function/loops, and printTime(start)
right after the block.
and you got the answer.
Try this using regular expression:
import re
data['result'] = data['result'].map(lambda x: re.sub('[-+A-Za-z]',x)
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
using facebook sdk in android studio is quite simple , just add the following line in your gradle
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
and make sure that you have updated Android support repository , if not then update it using stand alone sdk manger
Here is my super basic solution that might not work for everyone. But would work for a lot of people.
It requires usage of the Guideline Support Library. Which is a pretty official C++ library that was designed by many C++ committee authors:
std::string to_string(std::wstring const & wStr)
{
std::string temp = {};
for (wchar_t const & wCh : wStr)
{
// If the string can't be converted gsl::narrow will throw
temp.push_back(gsl::narrow<char>(wCh));
}
return temp;
}
All my function does is allow the conversion if possible. Otherwise throw an exception.
Via the usage of gsl::narrow (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es49-if-you-must-use-a-cast-use-a-named-cast)
The second method, Task.Run
, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew
, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run
doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run
, while you can do so with the Task.Factory.StartNew
, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the new Task.Run method. This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters. It’s a shortcut. In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters. When you pass an Action to Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
Just adding this for multiple filters attaching to Q
object, if someone might be looking to it.
If a Q
object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.
an example would be
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')
Here the OR condition and a filter with category of income is taken into account
Connect to the database, then list the tables:
\c liferay
\dt
That's how I do it anyway.
You can combine those two commands onto a single line, if you prefer:
\c liferay \dt
This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends
flag:
apt-get install -y python
I had the same problem recently and this helped me:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
It's not that above answers are incorrect, but I find this code extremely easy to understand and therefore I am sharing it here with everyone. And there is also the check for WRITE_CONTACTS
permission.
Here is the complete code for how to add phone number, email, website etc to an existing contact.
public static void addNumberToContact(Context context, Long contactRawId, String number) throws RemoteException, OperationApplicationException {
addInfoToAddressBookContact(
context,
contactRawId,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_OTHER,
number
);
}
public static void addEmailToContact(Context context, Long contactRawId, String email) throws RemoteException, OperationApplicationException {
addInfoToAddressBookContact(
context,
contactRawId,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_OTHER,
email
);
}
public static void addURLToContact(Context context, Long contactRawId, String url) throws RemoteException, OperationApplicationException {
addInfoToAddressBookContact(
context,
contactRawId,
ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Website.URL,
ContactsContract.CommonDataKinds.Website.TYPE,
ContactsContract.CommonDataKinds.Website.TYPE_OTHER,
url
);
}
private static void addInfoToAddressBookContact(Context context, Long contactRawId, String mimeType, String whatToAdd, String typeKey, int type, String data) throws RemoteException, OperationApplicationException {
if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) {
return;
}
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, contactRawId)
.withValue(ContactsContract.Data.MIMETYPE, mimeType)
.withValue(whatToAdd, data)
.withValue(typeKey, type)
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
Since you can scp
you should be ok to ssh
,
either script the following or login and execute...
# After reaching the server of interest
cd /usr/some/unknown/number/of/sub/folders
tar cfj pack.tar.bz2 $(find . -type f -name *.class)
return back (logout) to local server and scp
,
# from the local machine
cd /usr/project/backup/some/unknown/number/of/sub/folders
scp you@server:/usr/some/unknown/number/of/sub/folders/pack.tar.bz2 .
tar xfj pack.tar.bz2
If you find the $(find ...)
is too long for your tar change to,
find . -type f -name *.class | xargs tar cfj pack.tar.bz2
Finally, since you are keeping it in /usr/project/backup/
,
why bother extraction? Just keep the tar.bz2
, with maybe a date+time stamp.
Not sure if it's what you mean, but you can do this:
plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])
which then gives you the graph:
The cause of the error is the use of the internal PHP programming data structures function, array_shift() [php.net/end].
The function takes an array as a parameter. Although an ampersand is indicated in the prototype of array_shift()
in the manual", there isn't any cautionary documentation following in the extended definition of that function, nor is there any apparent explanation that the parameter is in fact passed by reference.
Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.
Reproduce code:
function get_arr()
{
return array(1, 2);
}
$array = get_arr();
$el = array_shift($array);
see this situation:
typedef struct tagPyTypeObject
{
PyObject_HEAD;
char *name;
PrintFun print;
AddFun add;
HashFun hash;
} PyTypeObject;
PyTypeObject PyDict_Type=
{
PyObject_HEAD_INIT(&PyType_Type),
"dict",
dict_print,
0,
0
};
watch the name field, in gcc it compile without warning, but in g++ it will, i don't know why.
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Your declaration is int ttTreeInsert(int value);
However, your definition/implementation is
ttTree::ttTreeInsert(int value)
{
}
Notice that the return type int
is missing in the implementation. Instead it should be
int ttTree::ttTreeInsert(int value)
{
return 1; // or some valid int
}
Slight bias to SQL Server
Summary
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
SQL Server 2008 has date
type though. So just use
CAST(GETDATE() AS DATE)
Edit: To add one day, compare to the day before "zero"
DATEADD(day, DATEDIFF(day, -1, GETDATE()), 0)
From cyberkiwi:
An alternative that does not involve 2 functions is (the +1 can be in or ourside the brackets).
DATEDIFF(DAY, 0, GETDATE() +1)
DateDiff
returns a number but for all purposes this will work as a date wherever you intend to use this expression, except converting it to VARCHAR directly - in which case you would have used the CONVERT approach directly on GETDATE(), e.g.
convert(varchar, GETDATE() +1, 102)
If you created ImageView
from Java Class
ImageView img = new ImageView(this);
//Here we are setting the image in image view
img.setImageResource(R.drawable.my_image);
Avoid loops. What you want to do is:
import numpy as np
data=np.loadtxt(fname="data.txt")## to load the above two column
print data
print data.sum(axis=1)
If you want to show just numbers without characters, put this line of code inside your XML file android:inputType="number"
. The output:
If you want to show a number keyboard that also shows characters, put android:inputType="phone"
on your XML. The output (with characters):
And if you want to show a number keyboard that masks your input just like a password, put android:inputType="numberpassword"
. The output:
I'm really sorry if I only post the links of the screenshot, I want to do research on how to do really post images here but it might consume my time so here it is. I hope my post can help other people. Yes, my answer is duplicate with other answers posted here but to save other people's time that they might need to run their code before seeing the output, my post might save you some time.
Linux operating system offers different types of shell. Though shells have many commands in common, each type has unique features. Let’s study different kind of mostly used shells.
Sh shell:
Sh shell is also known as Bourne Shell. Sh shell is the first shell developed for Unix computers by Stephen Bourne at AT&T's Bell Labs in 1977. It include many scripting tools.
Bash shell :
Bash shell stands for Bourne Again Shell. Bash shell is the default shell in most linux distribution and substitute for Sh Shell (Sh shell will also run in the Bash shell) . Bash Shell can execute the vast majority of Sh shell scripts without modification and provide commands line editing feature also.
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;
}
You could use pandas.concat()
or DataFrame.append()
. For details and examples, see Merge, join, and concatenate.
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
A GUID is theoretically non-unique. Here's your proof:
However, if the entire power output of the sun was directed at performing this task, it would go cold long before it finished.
GUIDs can be generated using a number of different tactics, some of which take special measures to guarantee that a given machine will not generate the same GUID twice. Finding collisions in a particular algorithm would show that your particular method for generating GUIDs is bad, but would not prove anything about GUIDs in general.
I've seen some people promote 'package by feature' over 'package by layer' but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that I have found that a hybrid: 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
I explain in depth here: Java Package Name Structure and Organization but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain e.g. com.mycompany
moduleType [app*|framework|util]
moduleName e.g. myAppName if module type is an app or 'finance' if its an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl eg., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature eg., finance
subfeatureN eg., accounting
subfeatureN+1 eg., depreciation
*Sometimes 'app' left out if moduleType is an application but putting it in there makes the package structure consistent across all module types.
SHOW STATUS WHERE `variable_name` = 'Threads_connected';
This will show you all the open connections.
Most of these answers are now outdated, IE7 support is not an issue.
The best way to do this that supports IE11+ and all modern browsers is:
const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');
Or if you want, you can create a small jQuery plugin that does this.
This plugin closely matches jQuery's own css()
method in the parameters it supports:
/**
* Sets a CSS style on the selected element(s) with !important priority.
* This supports camelCased CSS style property names and calling with an object
* like the jQuery `css()` method.
* Unlike jQuery's css() this does NOT work as a getter.
*
* @param {string|Object<string, string>} name
* @param {string|undefined} value
*/
jQuery.fn.cssImportant = function(name, value) {
const $this = this;
const applyStyles = (n, v) => {
// Convert style name from camelCase to dashed-case.
const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
return m1 + "-" + upper.toLowerCase() + m2;
});
// Loop over each element in the selector and set the styles.
$this.each(function(){
this.style.setProperty(dashedName, v, 'important');
});
};
// If called with the first parameter that is an object,
// Loop over the entries in the object and apply those styles.
if(jQuery.isPlainObject(name)){
for(const [n, v] of Object.entries(name)){
applyStyles(n, v);
}
} else {
// Otherwise called with style name and value.
applyStyles(name, value);
}
// This is required for making jQuery plugin calls chainable.
return $this;
};
// Call the new plugin:
$('#elem').cssImportant('height', '100px');
// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});
// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
var x = document.getElementById("parent").querySelector("#child");
// don't forget a #
or
var x = document.querySelector("#parent").querySelector("#child");
or
var x = document.querySelector("#parent #child");
or
var x = document.querySelector("#parent");
var y = x.querySelector("#child");
eg.
var x = document.querySelector("#div1").querySelector("#edit2");
myString.Contain("someString"); // equal with myString LIKE '%someString%'
myString.EndWith("someString"); // equal with myString LIKE '%someString'
myString.StartWith("someString"); // equal with myString LIKE 'someString%'
In java.util.timer one can use .cancel()
to stop the timer and clear all pending tasks.
This is something I just recently had to do:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
(
@CustomerID AS INT,
@UserName AS VARCHAR(25),
@Password AS BINARY(16)
)
AS
BEGIN
IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
BEGIN
INSERT INTO [tblOnline_CustomerAccount] (
[CustomerID],
[UserName],
[Password],
[LastLogin]
) VALUES (
/* CustomerID - int */ @CustomerID,
/* UserName - varchar(25) */ @UserName,
/* Password - binary(16) */ @Password,
/* LastLogin - datetime */ NULL )
END
ELSE
BEGIN
UPDATE [tblOnline_CustomerAccount]
SET UserName = @UserName,
Password = @Password
WHERE CustomerID = @CustomerID
END
END
Using variable indirection to refer directly to an array also works. Named references can also be used, but they only became available in 4.3.
The advantage of using this form of a function is that you can have the separator optional (defaults to the first character of default IFS
, which is a space; perhaps make it an empty string if you like), and it avoids expanding values twice (first when passed as parameters, and second as "$@"
inside the function).
This solution also doesn't require the user to call the function inside a command substitution - which summons a subshell, to get a joined version of a string assigned to another variable.
function join_by_ref {
__=
local __r=$1[@] __s=${2-' '}
printf -v __ "${__s//\%/%%}%s" "${!__r}"
__=${__:${#__s}}
}
array=(1 2 3 4)
join_by_ref array
echo "$__" # Prints '1 2 3 4'.
join_by_ref array '%s'
echo "$__" # Prints '1%s2%s3%s4'.
join_by_ref 'invalid*' '%s' # Bash 4.4 shows "invalid*[@]: bad substitution".
echo "$__" # Prints nothing but newline.
Feel free to use a more comfortable name for the function.
This works from 3.1 to 5.0-alpha. As observed, variable indirection doesn't only work with variables but with other parameters as well.
A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below under Special Parameters. A variable is a parameter denoted by a name.
Arrays and array elements are also parameters (entities that store value), and references to arrays are technically references to parameters as well. And much like the special parameter @
, array[@]
also makes a valid reference.
Altered or selective forms of expansion (like substring expansion) that deviate reference from the parameter itself no longer work.
In the release version of Bash 5.0, variable indirection is already called indirect expansion and its behavior is already explicitly documented in the manual:
If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion.
Taking note that in the documentation of ${parameter}
, parameter
is referred to as "a shell parameter as described (in) PARAMETERS or an array reference". And in the documentation of arrays, it is mentioned that "Any element of an array may be referenced using ${name[subscript]}
". This makes __r[@]
an array reference.
See my comment in Riccardo Galli's answer.
For me, I got similar error when switched between branches - one used newer ("typescriptish") version of @google-cloud/datastore
packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports
value. I got the error because node_modules still had newer modules used by branch I switched from.
For getting key
var a = {"a":"1","b":"2"};
var keys = []
for(var k in a){
keys.push(k)
}
For getting value.
var a = {"a":"1","b":"2"};
var values = []
for(var k in a){
values.push(a[k]);
}
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
add JAVA_HOME to the file:
/etc/environment
for it to be available to the entire system (you would need to restart Ubuntu though)
Bootstrap styling for jQuery UI Autocomplete
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
padding: 4px 0;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
text-decoration: none;
}
.ui-state-hover, .ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
how about in vuejs how is it applicable?
function onClick() {_x000D_
var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
pdf.canvas.height = 72 * 11;_x000D_
pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
pdf.fromHTML(document.body);_x000D_
_x000D_
pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
Create the following function
CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
"is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'
And it'll work.
You may to create different versions with different parameter types.
I'm a full-blown Emacs fan-boy, but I knew VI long before I knew Emacs. That said, I make all of my people learn VI because it's always available, everywhere. Can't go wrong with either one of them.
Another solution using java.nio.file
:
byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
I found to be the best practice of using images, videos, etc. is:
<Image Source="/WPFApplication;component/Images/Start.png" />
Benefits:
That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception may be an issue.
You can check in windows services if tomcat is installed it will be listed in windows services.
To check the windows service list of services installed on windows machine use
WINDOWS KEY + R and type services.msc
There you can find all the services related with Jasperreport server like Tomcat and MySQL with name starting Jasperreport server Tomcat and MySQL only if these services are installed and its need to be started by selecting the option.Then you can access it through browser using this link :-
http://localhost:8080
default port for tomcat is 8080.
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
You can also use ISNULL and a select statement to get this result
SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1
You can solve this with a one-liner( errStringified ) in plain javascript:
var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);
It works with DOMExceptions as well.
yan.kun was on the right track but this is much much easier.
public FileContentResult DownloadCSV()
{
string csv = "Charlie, Chaplin, Chuckles";
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
}
A one liner:
perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
Here's how I did it:
var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
delete keystate[e.keyCode];
});
if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}
As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.
Definition here
What is the difference between an abstract class and an interface? When would you use each of them?
Lots of Java developers don't know this, I asked most people on my computer science course at university and the vast majority could not answer it.
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
I recomend library assertj-core
to handle exception in junit test
In java 8, like this:
//given
//when
Throwable throwable = catchThrowable(() -> anyService.anyMethod(object));
//then
AnyException anyException = (AnyException) throwable;
assertThat(anyException.getMessage()).isEqualTo("........");
assertThat(exception.getCode()).isEqualTo(".......);
(This is the KISS answer.)
Let's say you have several .java files in the current directory:
$ ls -1 *.java
javaFileName1.java
javaFileName2.java
Let's say each of them have a main()
method (so they are programs, not libs), then to compile them do:
javac *.java -d .
This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName
, so only one folder was generated with that name, so to execute each of them:
java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.
File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)
if
takes a command and checks its return value. [
is just a command.
if grep -q ...
then
....
else
....
fi
I'm using react-router ScrollToTop Component which code described in react-router docs
https://reacttraining.com/react-router/web/guides/scroll-restoration/scroll-to-top
I'm changing code in single Routes file and after that no need of change code in every component.
Example Code -
Step 1 - create ScrollToTop.js Component
import React, { Component } from 'react';
import { withRouter } from 'react-router';
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
Step 2 - In App.js file, add ScrollToTop Component after <Router
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
This helped me:
Posted: 8/12/2011 4:54
Set tnsnames directory tools->Preferences->Database->advanced->Tnsnames Directory
https://forums.oracle.com/forums/thread.jspa?messageID=10020012�
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
Also, you can use shelljs
plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
the worked proposition for me is __call__
on class who create list of little numbers:
import itertools
class SmallNumbers:
def __init__(self, how_much):
self.how_much = int(how_much)
self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
start = 10
end = 100
for cmb in range(2, len(str(self.how_much)) + 1):
self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
start *= 10
end *= 10
def __call__(self, number, *args, **kwargs):
return self.generated_list[number]
def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
multi_work_list = eval(str('self.work_list,') * combinations)
nbr = 0
for subset in itertools.product(*multi_work_list):
if is_upper_then <= nbr < is_under_then:
self.generated_list.append(''.join(subset))
if self.how_much == nbr:
break
nbr += 1
and to run it:
if __name__ == '__main__':
sm = SmallNumbers(56)
print(sm.generated_list)
print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
print('The Best', sm(15), sm(55), sm(49), sm(0))
result
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0
You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)
Your query apparently returned all correct dates, even considering the time.
If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.
Make sure your mydate
column is a datetime
type.
For setting java properties on Windows app server:
then add Java opts:
restart service.
If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.
This worked for me on my local machine
The man page makes it pretty clear. If you want to pass two arguments (-rpath
and .
) to the linker you can write
-Wl,-rpath,.
or alternatively
-Wl,-rpath -Wl,.
The arguments -Wl,-rpath .
you suggested do NOT make sense to my mind. How is gcc supposed to know that your second argument (.
) is supposed to be passed to the linker instead of being interpreted normally? The only way it would be able to know that is if it had insider knowledge of all possible linker arguments so it knew that -rpath
required an argument after it.
public Bitmap bitmapResize(Bitmap imageBitmap) {
Bitmap bitmap = imageBitmap;
float heightbmp = bitmap.getHeight();
float widthbmp = bitmap.getWidth();
// Get Screen width
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float height = displaymetrics.heightPixels / 3;
float width = displaymetrics.widthPixels / 3;
int convertHeight = (int) hight, convertWidth = (int) width;
// higher
if (heightbmp > height) {
convertHeight = (int) height - 20;
bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
convertHighet, true);
}
// wider
if (widthbmp > width) {
convertWidth = (int) width - 20;
bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
convertHeight, true);
}
return bitmap;
}
In addition to the Onur's answer, You possibly want to deal with datetime type like below.
(in order to handle: 'datetime.datetime' object has no attribute 'dict' exception.)
def datetime_option(value):
if isinstance(value, datetime.date):
return value.timestamp()
else:
return value.__dict__
Usage:
def toJSON(self):
return json.dumps(self, default=datetime_option, sort_keys=True, indent=4)
You either want to select an anonymous type:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
select new
{
recordset.ServerName,
recordset.ProcessID,
recordset.Username
};
But you cannot cast that to another type, so I guess you want something like this:
var dataset2 = from recordset
in entities.processlists
where recordset.ProcessName == processname
// Select new concrete type
select new PInfo
{
ServerName = recordset.ServerName,
ProcessID = recordset.ProcessID,
Username = recordset.Username
};
You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog
class.
Adding using WinForms = System.Windows.Forms;
will be helpful.
int(round(x))
Will round it and change it to integer
EDIT:
You are not assigning int(round(h)) to any variable. When you call int(round(h)), it returns the integer number but does nothing else; you have to change that line for:
h = int(round(h))
To assign the new value to h
EDIT 2:
As @plowman said in the comments, Python's round()
doesn't work as one would normally expect, and that's because the way the number is stored as a variable is usually not the way you see it on screen. There are lots of answers that explain this behavior:
round() doesn't seem to be rounding properly
One way to avoid this problem is to use the Decimal as stated by this answer: https://stackoverflow.com/a/15398691/4345659
In order for this answer to work properly without using extra libraries it would be convenient to use a custom rounding function. After a lot of corrections, I came up with the following solution, that as far as I tested avoided all the storing issues. It is based on using the string representation, obtained with repr()
(NOT str()
!). It looks hacky but it was the only way I found to solve all the cases. It works with both Python2 and Python3.
def proper_round(num, dec=0):
num = str(num)[:str(num).index('.')+dec+2]
if num[-1]>='5':
return float(num[:-2-(not dec)]+str(int(num[-2-(not dec)])+1))
return float(num[:-1])
Tests:
>>> print(proper_round(1.0005,3))
1.001
>>> print(proper_round(2.0005,3))
2.001
>>> print(proper_round(3.0005,3))
3.001
>>> print(proper_round(4.0005,3))
4.001
>>> print(proper_round(5.0005,3))
5.001
>>> print(proper_round(1.005,2))
1.01
>>> print(proper_round(2.005,2))
2.01
>>> print(proper_round(3.005,2))
3.01
>>> print(proper_round(4.005,2))
4.01
>>> print(proper_round(5.005,2))
5.01
>>> print(proper_round(1.05,1))
1.1
>>> print(proper_round(2.05,1))
2.1
>>> print(proper_round(3.05,1))
3.1
>>> print(proper_round(4.05,1))
4.1
>>> print(proper_round(5.05,1))
5.1
>>> print(proper_round(1.5))
2.0
>>> print(proper_round(2.5))
3.0
>>> print(proper_round(3.5))
4.0
>>> print(proper_round(4.5))
5.0
>>> print(proper_round(5.5))
6.0
>>>
>>> print(proper_round(1.000499999999,3))
1.0
>>> print(proper_round(2.000499999999,3))
2.0
>>> print(proper_round(3.000499999999,3))
3.0
>>> print(proper_round(4.000499999999,3))
4.0
>>> print(proper_round(5.000499999999,3))
5.0
>>> print(proper_round(1.00499999999,2))
1.0
>>> print(proper_round(2.00499999999,2))
2.0
>>> print(proper_round(3.00499999999,2))
3.0
>>> print(proper_round(4.00499999999,2))
4.0
>>> print(proper_round(5.00499999999,2))
5.0
>>> print(proper_round(1.0499999999,1))
1.0
>>> print(proper_round(2.0499999999,1))
2.0
>>> print(proper_round(3.0499999999,1))
3.0
>>> print(proper_round(4.0499999999,1))
4.0
>>> print(proper_round(5.0499999999,1))
5.0
>>> print(proper_round(1.499999999))
1.0
>>> print(proper_round(2.499999999))
2.0
>>> print(proper_round(3.499999999))
3.0
>>> print(proper_round(4.499999999))
4.0
>>> print(proper_round(5.499999999))
5.0
Finally, the corrected answer would be:
# Having proper_round defined as previously stated
h = int(proper_round(h))
EDIT 3:
Tests:
>>> proper_round(6.39764125, 2)
6.31 # should be 6.4
>>> proper_round(6.9764125, 1)
6.1 # should be 7
The gotcha here is that the dec
-th decimal can be 9 and if the dec+1
-th digit >=5 the 9 will become a 0 and a 1 should be carried to the dec-1
-th digit.
If we take this into consideration, we get:
def proper_round(num, dec=0):
num = str(num)[:str(num).index('.')+dec+2]
if num[-1]>='5':
a = num[:-2-(not dec)] # integer part
b = int(num[-2-(not dec)])+1 # decimal part
return float(a)+b**(-dec+1) if a and b == 10 else float(a+str(b))
return float(num[:-1])
In the situation described above b = 10
and the previous version would just concatenate a
and b
which would result in a concatenation of 10
where the trailing 0 would disappear. This version transforms b
to the right decimal place based on dec
, as a proper carry.
Its pretty simple. Assume that your classname is Car
and the namespace is Vehicles
, then pass the parameter as Vehicles.Car
which returns object of type Car
. Like this you can create any instance of any class dynamically.
public object GetInstance(string strNamesapace)
{
Type t = Type.GetType(strNamesapace);
return Activator.CreateInstance(t);
}
If your Fully Qualified Name(ie, Vehicles.Car
in this case) is in another assembly, the Type.GetType
will be null. In such cases, you have loop through all assemblies and find the Type
. For that you can use the below code
public object GetInstance(string strFullyQualifiedName)
{
Type type = Type.GetType(strFullyQualifiedName);
if (type != null)
return Activator.CreateInstance(type);
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
type = asm.GetType(strFullyQualifiedName);
if (type != null)
return Activator.CreateInstance(type);
}
return null;
}
And you can get the instance by calling the above method.
object objClassInstance = GetInstance("Vehicles.Car");
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
This is a simple way to test this for the current page URL:
function checkHash(){
return (location.hash ? true : false);
}
The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.
Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.
If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation
Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));
Or
Assert.assertEquals(0, Double.compareTo(expected, result));
Which can take these nuances into account.
I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.
I add this answer because I think it could be useful to anybody.
I step into the problem of setting RGBA colors (that is, RGB color with an Alpha value for transparency) for color display labels in my painting application.
As I came across the first answer, I was unable to set an RGBA color. I have also tried things like:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
where color
is an RGBA color.
So, my dirty solution was to extend QLabel
and override paintEvent()
method filling its bounding rect.
Today, I've open up the qt-assistant
and read the style reference properties list. Affortunately, it has an example that states the following:
QLineEdit { background-color: rgb(255, 0, 0) }
Thats open up my mind in doing something like the code below, as an example:
myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color = QtGui.QColor(233, 10, 150)
alpha = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
g = color.green(),
b = color.blue(),
a = alpha
)
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
Note that setAutoFillBackground()
set in False
will not make it work.
Regards,
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("tr1").show();
$("tr1").hide();
You just need a loop that iterates the number of times given by n
and prints a space each time. This would do:
while (n--) {
std::cout << ' ';
}