first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
As the other answers suggest, editing/removing credentials in the Manage Windows Credentials
work and does the job. However, you need to do this each time when the password changes or credentials do not work for some work. Using ssh key
has been extremely useful for me where I don't have to bother about these again once I'm done creating a ssh-key
and adding them on the server repository (github/bitbucket/gitlab).
Generating a new ssh-key
Open Git Bash.
Paste the text below, substituting in your repo's email address.
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
Then you'll be asked to type a secure passphrase. You can type a passphrase, hit enter and type the passphrase again.
Or, Hit enter twice for empty passphrase.
Copy this on the clipboard:
clip < ~/.ssh/id_rsa.pub
And then add this key into your repo's profile. For e.g, on github->setting->SSH keys -> paste the key that you coppied ad hit add
You're done once and for all!
I spent over 5 hours trying to get rid of this message under Windows 8.1. So I would like to share my case and save someones time. I was not behind the proxy... but setting proxy helped to resolve the problem. So I go deep and found that issue was caused by Comodo Firewall... which blocked cmd since I was installing packages too fast (turning off and even closing Firewall did not help, which caused me so long to find the issue... seems like there was some other process of Firewall running in background). You may have same issue with any other firewall/antivirus installed so make sure that cmd is not blocked by them. Good luck!
the best way to concat props/variables:
var sample = "test";
var result = `this is just a ${sample}`;
//this is just a test
I think this has been officially implemented now: https://jenkins.io/blog/2017/09/25/declarative-1/
I have encountered the same issue. This command didn't work for me either:
npm config set strict-ssl false
After digging deeper, I found out that this link was block by our IT admin.
http://registry.npmjs.org/npm
So if you are facing the same issue, make sure this link is accessible to your browser first.
About this, java declares that on Windows 10, Edge browser does not support plugins, so it will NOT run java. (see https://www.java.com/it/download/win10.jsp --> only visible with edge in win10) It also reports a notice: java is not officially supported yet in Windows 10. (see https://www.java.com/it/download/faq/win10_faq.xml)
// you can get the Jquery's librairies online with adding those two rows in your page
<script type="text/javascript" src=" https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
Developer Preview 2 brings some changes to how permissions are requested by the app (see also http://developer.android.com/preview/support.html#preview2-notes).
The first dialog now looks like this:
There's no "Never show again" check-box (unlike developer preview 1). If the user denies the permission and if the permission is essential for the app it could present another dialog to explain the reason the app asks for that permission, e.g. like this:
If the user declines again the app should either shut down if it absolutely needs that permission or keep running with limited functionality. If the user reconsiders (and selects re-try), the permission is requested again. This time the prompt looks like this:
The second time the "Never ask again" check-box is shown. If the user denies again and the check-box is ticked nothing more should happen. Whether or not the check-box is ticked can be determined by using Activity.shouldShowRequestPermissionRationale(String), e.g. like this:
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {...
That's what the Android documentation says (https://developer.android.com/training/permissions/requesting.html):
To help find the situations where you need to provide extra explanation, the system provides the Activity.shouldShowRequestPermissionRationale(String) method. This method returns true if the app has requested this permission previously and the user denied the request. That indicates that you should probably explain to the user why you need the permission.
If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false. The method also returns false if the device policy prohibits the app from having that permission.
To know if the user denied with "never ask again" you can check again the shouldShowRequestPermissionRationale method in your onRequestPermissionsResult when the user did not grant the permission.
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
// for each permission check if the user granted/denied them
// you may want to group the rationale in a single dialog,
// this is just an example
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
// user rejected the permission
boolean showRationale = shouldShowRequestPermissionRationale( permission );
if (! showRationale) {
// user also CHECKED "never ask again"
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
} else if (Manifest.permission.WRITE_CONTACTS.equals(permission)) {
showRationale(permission, R.string.permission_denied_contacts);
// user did NOT check "never ask again"
// this is a good place to explain the user
// why you need the permission and ask if he wants
// to accept it (the rationale)
} else if ( /* possibly check more permissions...*/ ) {
}
}
}
}
}
You can open your app setting with this code:
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
There is no way of sending the user directly to the Authorization page.
More from Bill Phillip's article (go read it!) but i thought it was important to point out the following.
In ListView, there was some ambiguity about how to handle click events: Should the individual views handle those events, or should the ListView handle them through OnItemClickListener? In RecyclerView, though, the ViewHolder is in a clear position to act as a row-level controller object that handles those kinds of details.
We saw earlier that LayoutManager handled positioning views, and ItemAnimator handled animating them. ViewHolder is the last piece: it’s responsible for handling any events that occur on a specific item that RecyclerView displays.
how about this?
fun <- function(x, ...){
y=NULL
parms=list(...)
for (name in names(parms) ) {
assign(name, parms[[name]])
}
print(is.null(y))
}
Then try:
> fun(1,y=4)
[1] FALSE
> fun(1)
[1] TRUE
Tried everything in this thread and nothing worked for me in IntelliJ 2020.2. This answer did the trick, but I had to set the correct path to the JDK and choose it in Gradle settings after that (as showed in figures bellow):
After that, the option "Reload All Gradle Projects" downloaded all dependencies as expected.
Cheers.
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
ymptom: After configuring Nexus to serve SSL maven builds fail with "peer not authenticated" or "PKIX path building failed".
This is usually caused by using a self signed SSL certificate on Nexus. Java does not consider these to be a valid certificates, and will not allow connecting to server's running them by default.
You have a few choices here to fix this:
For option 1 you can use the keytool command and follow the steps in the below article.
Explicitly Trusting a Self-Signed or Private Certificate in a Java Based Client
For option 3, invoke Maven with "-Dmaven.wagon.http.ssl.insecure=true". If the host name configured in the certificate doesn't match the host name Nexus is running on you may also need to add "-Dmaven.wagon.http.ssl.allowall=true".
Note: These additional parameters are initialized in static initializers, so they have to be passed in via the MAVEN_OPTS environment variable. Passing them on the command line to Maven will not work.
See here for more information:
If you're behind a proxy, the very first thing to do is, add settings.xml
with proxy configs under C:\Users\{username}\.m2
folder, and replicate same proxy configs under Window > Preferences > Network Connections
(you may need to prefix your user name with domain eg. DOMAIN\username
):
<settings>
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>webproxy.net</host>
<port>8080</port>
<username>username</username>
<password>password</password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
<proxy>
<active>true</active>
<protocol>https</protocol>
<host>webproxy.net</host>
<port>8080</port>
<username>username</username>
<password>password</password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
Delete C:\Users\{username}\.m2\repository
folder as well.
Try this, it was the only that worked for me:
npm --proxy http://:@proxyhost: --https-proxy http://:@proxyhost: --strict-ssl false install -g package
Pay atention to the option --strict-ssl false
Good luck.
If you want an alert that is fixed to the top and you are using bootstrap navbar navbar-fixed-top the following style class will overlay they alert on top of the nav:
.alert-fixed {
position:fixed;
top: 0px;
left: 0px;
width: 100%;
z-index:9999;
border-radius:0px
}
This worked well for me to provide alerts even when the user is scrolled down in the page.
The best solution is to save a Boolean value in the database and then obtain that value and validate whether or not the modal was opened for that user, this value could be in the user table for example.
Open Git Bash and run the command if you want to completely disable SSL verification.
git config --global http.sslVerify false
Note: This solution may open you to attacks like man-in-the-middle attacks. Therefore turn on verification again as soon as possible:
git config --global http.sslVerify true
Your mail won't be sent online unless you complete the two-step verification for your g-mail account and use that password.
In my case, (windows OS), after put all those commands listed, npm kept taking the proxy in the setting of windows registry
\ HKEY_CURRENT_USER \ Environment
just remove the proxy settings there, after that, I restarted the pc and then "npm install" worked for me
UPDATE:
compile 'com.android.volley:volley:1.0.0'
OLD ANSWER: You need the next in your build.gradle of your app module:
dependencies {
compile 'com.mcxiaoke.volley:library:1.0.19'
(Rest of your dependencies)
}
This is not the official repo but is a highly trusted one.
Situation: Working in my local branch, but I love to keep-up updates in the development branch named dev
.
Solution: Usually, I prefer to do :
git fetch
git rebase origin/dev
My recomendation is to keep the getRuntime().exec
because exec
uses the ProcessBuilder
.
Try
p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);
urllib2 does not verify server certificate by default. Check this documentation.
Edit: As pointed out in below comment, this is not true anymore for newer versions (seems like >= 2.7.9) of Python. Refer the below ANSWER
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
<a href="deletelink" onclick="return confirm('Are you sure?')">Delete</a>
In a function:
<a href="deletelink" onclick="return checkDelete()">Delete</a>
and then put this in <head>
:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
<a href="deletelink" class="delete">Delete</a>
And put this in <head>
:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>
For me this works perfect
insert into oehr.employees select * from employees where employee_id=99
I am not sure why you get error. The nature of the error code you have produced is the columns didn't match.
One good approach will be to use the answer @Parodo specified
While not a Nodejs setting, I suggest you use proxychains which I find rather convenient. It is probably available in your package manager.
After setting the proxy in the config file (/etc/proxychains.conf
for me), you can run proxychains npm start
or proxychains4 npm start
(i.e. proxychains [command_to_proxy_transparently]
) and all your requests will be proxied automatically.
Config settings for me:
These are the minimal settings you will have to append
## Exclude all localhost connections (dbs and stuff)
localnet 0.0.0.0/0.0.0.0
## Set the proxy type, ip and port here
http 10.4.20.103 8080
(You can get the ip of the proxy by using nslookup [proxyurl]
)
do not forget to insert (or unCommanet) this line at the beginning of your pod file:
platform :iOS, '9.0'
that saves my day
It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.
df <- data.frame(
X1=seq(0, 5, by=0.001),
X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)
# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf),
labels = c("low", "medium", "high"),
right = FALSE)
### Base Graphics
plot(df$X1, df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 21)
plot(df$X1,df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)
# Using `with()`
with(df,
plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
)
# Using ggplot2
library(ggplot2)
# qplot()
qplot(df$X1, df$X2, colour = df$Colour)
# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour))
p <- p + geom_point() + xlab("POS") + ylab("CS")
p
p + facet_grid(Colour~., scales = "free")
We can divide data into a particular ratio here it is 80% train and 20% in a test dataset.
ind <- sample(2, nrow(dataName), replace = T, prob = c(0.8,0.2))
train <- dataName[ind==1, ]
test <- dataName[ind==2, ]
Chrome does not allow autoplay if the video is not muted. Try using this:
<video width="440px" loop="true" autoplay="autoplay" controls muted>
<source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
<source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
<source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>
function readURL(input) {_x000D_
if (input.files && input.files[0]) {_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onload = function(e) {_x000D_
$('#ImdID').attr('src', e.target.result);_x000D_
};_x000D_
_x000D_
reader.readAsDataURL(input.files[0]);_x000D_
}_x000D_
}
_x000D_
img {_x000D_
max-width: 180px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type='file' onchange="readURL(this);" />_x000D_
<img id="ImdID" src="" alt="Image" />
_x000D_
write.csv([enter name of dataframe here],file = file.choose(new = T))
After running above script this window will open :
Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.
I realize this is an old question and has been answered but this could help someone.
In your activity
private ScheduledExecutorService scheduleTaskExecutor;
In onCreate
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
//Schedule a task to run every 5 seconds (or however long you want)
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// Do stuff here!
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do stuff to update UI here!
Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.
Use CSS :
input[type=submit] {
background:url("BUTTON1.jpg");
}
For HTML :
<input type="submit" value="Login" style="background:url("BUTTON1.jpg");">
I faced the same error with my Visual Studio Team Services account (formerly Visual Studio Online, Team Foundation Service).
I simply entered the credentials using the VS 2013 "Connect to Team Foundation Server" Window, and then connected it to the Visual Studio Team Services Team Project. It worked this way.
One way to do it is the code below:
int gcd = 0;
while (gcdNum2 !=0 && gcdNum1 != 0 ) {
if(gcdNum1 % gcdNum2 == 0){
gcd = gcdNum2;
}
int aux = gcdNum2;
gcdNum2 = gcdNum1 % gcdNum2;
gcdNum1 = aux;
}
You do not need recursion to do this.
And be careful, it says that when a number is zero, then the GCD is the number that is not zero.
while (gcdNum1 == 0) {
gcdNum1 = 0;
}
You should modify this to fulfill the requirement.
I am not going to tell you how to modify your code entirely, only how to calculate the gcd.
Winston is a pretty good logging library. You can write logs out to a file using it.
Code would look something like:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
module.exports = logger;
You can then use this like:
var logger = require('./log');
logger.info('log to file');
Here is the approach I have taken to finding addresses using regular expressions:
A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.
Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.
import re
strings = [
'701 FIFTH AVE',
'2157 Henderson Highway',
'Attn: Patent Docketing',
'HOLLYWOOD, FL 33022-2480',
'1940 DUKE STREET',
'111 MONUMENT CIRCLE, SUITE 3700',
'c/o Armstrong Teasdale LLP',
'1 Almaden Boulevard',
'999 Peachtree Street NE',
'P.O. BOX 2903',
'2040 MAIN STREET',
'300 North Meridian Street',
'465 Columbus Avenue',
'1441 SEAMIST DR.',
'2000 PENNSYLVANIA AVENUE, N.W.',
'465 Columbus Avenue',
'28 STATE STREET',
'P.O, Drawer 800889.',
'2200 CLARENDON BLVD.',
'840 NORTH PLANKINTON AVENUE',
'1025 Connecticut Avenue, NW',
'340 Commercial Street',
'799 Ninth Street, NW',
'11318 Lazarro Ln',
'P.O, Box 65745',
'c/o Ballard Spahr LLP',
'8210 SOUTHPARK TERRACE',
'1130 Connecticut Ave., NW, Suite 420',
'465 Columbus Avenue',
"BANNER & WITCOFF , LTD",
"CHIP LAW GROUP",
"HAMMER & ASSOCIATES, P.C.",
"MH2 TECHNOLOGY LAW GROUP, LLP",
]
patterns = [
"c\/o [\w ]{2,}",
"C\/O [\w ]{2,}",
"P.O\. [\w ]{2,}",
"P.O\, [\w ]{2,}",
"[\w\.]{2,5} BOX [\d]{2,8}",
"^[#\d]{1,7} [\w ]{2,}",
"[A-Z]{2,2} [\d]{5,5}",
"Attn: [\w]{2,}",
"ATTN: [\w]{2,}",
"Attention: [\w]{2,}",
"ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
pat_no = 1
for pattern in patterns:
match = re.search(pattern, string.strip())
if match:
print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
found_count += 1
pat_no += 1
print("-- Total: " + str(total_count) + " Found: " + str(found_count))
The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:
JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()
JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
virtualenv
is a tool to create isolated Python environments.The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into
/usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global
site-packages
directory? For instance, on a shared host.In all these cases,
virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
That's why people consider insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.
It sounds indeed like video streaming more than image streaming, as someone suggested. JPEG/PNG compression isn't targeted for these types of speeds, so forget them.
Imagine having a recording codec on your system that can realtime record an incoming video stream (your screen). A bit like Fraps perhaps. Then imagine a video playback codec on the other side (the remote client). As HD recorders can do it (record live and even playback live from the same HD), so should you, in the end. The HD surely can't deliver images quicker than you can read your display, so that isn't the bottleneck. The bottleneck are the video codecs. You'll find the encoder much more of a problem than the decoder, as all decoders are mostly free.
I'm not saying it's simple; I myself have used DirectShow to encode a video file, and it's not realtime by far. But given the right codec I'm convinced it can work.
-m
means the parent number.
From the git doc:
Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.
For example, if your commit tree is like below:
- A - D - E - F - master
\ /
B - C branch one
then git cherry-pick E
will produce the issue you faced.
git cherry-pick E -m 1
means using D-E
, while git cherry-pick E -m 2
means using B-C-E
.
The better pattern is to create a standalone BroadcastReceiver
. This insures that your app can respond to the broadcast, whether or not the Service
is running. In fact, using this pattern may remove the need for a constant-running Service
altogether.
Register the BroadcastReceiver
in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent
(Bundle
) to the Service
, and respond to it in onStartCommand()
.
Eg:
public class FooReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}
Determine the application pool used by the application and set the property of by setting Enable 32 bit applications to True. This can be done through advance settings of the application pool.
if you just want to check if one or the other element are present you can use this custom helper
Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
like this
{{#if_or elem1 elem2}}
{{elem1}} or {{elem2}} are present
{{else}}
not present
{{/if_or}}
if you also need to be able to have an "or" to compare function return values I would rather add another property that returns the desired result.
The templates should be logicless after all!
If you are trying to clone then you could use the git transport
For example: git clone git://github.com/fog/fog.git
Vaio ~/Myworks/Hero $ git clone git://github.com/fog/fog.git
Initialized empty Git repository in /home/nthillaiarasu/Myworks/Hero/fog/.git/
remote: Counting objects: 41138, done.
remote: Compressing objects: 100% (13176/13176), done.
remote: Total 41138 (delta 27218), reused 40493 (delta 26708)
Receiving objects: 100% (41138/41138), 5.22 MiB | 58 KiB/s, done.
Resolving deltas: 100% (27218/27218), done
URLs should be case insensitive unless there is a good reason why they are should not be.
This is not mandatory (it is not any part of an RFC) but it makes the communication and storage of URLs far more reliable.
If I have two pages on a website:
http://stackoverflow.com/ABOUT.html
and
http://stackoverflow.com/about.html
How should they differ? Maybe one is written 'shouting style' (caps) - but from an IA point of view, the distinction should never be made by a change in the case of the URL.
Moreover, it is easy to implement this in Apache - just use CheckSpelling On
from mod_Speling.
For Linux users, check the value of GIT_HOME
in your .env
file in the home directory.
cd home/<username>/
.env
file and check the value of GIT_HOME
and select the git path appropriatelyPS: If you are not able to find the .env
file, click on View
on the formatting tool bar, select Show hidden files
. You should be able to find the .env
file now.
You can use ave
:
df$count <- ave(df$num, df[,c("name","type")], FUN=length)
Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..
Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.
It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).
There are 2 main problems with static variables:
With Fastlane sigh's resign option you can do this very easily.
sigh resign -p <path-to-profile-with-mobileprovision-ext> -i <code-sighning-identity-of-your-app>
You can download the profile using sigh also, just before the command.
This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up
<a href="\\server\folder\path" target="_blank">click</a>
If there is a need in a fancy UI - then it will barely serve as a solution.
Note, you may also be interested in:
Custom web font not working in IE9
Which includes a more descriptive breakdown of the CSS you see below (and explains the tweaks that make it work better on IE6-9).
@font-face {
font-family: 'Bumble Bee';
src: url('bumblebee-webfont.eot');
src: local('?'),
url('bumblebee-webfont.woff') format('woff'),
url('bumblebee-webfont.ttf') format('truetype'),
url('bumblebee-webfont.svg#webfontg8dbVmxj') format('svg');
}
@font-face {
font-family: 'GestaReFogular';
src: url('gestareg-webfont.eot');
src: local('?'),
url('gestareg-webfont.woff') format('woff'),
url('gestareg-webfont.ttf') format('truetype'),
url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}
body {
background: #fff url(../images/body-bg-corporate.gif) repeat-x;
padding-bottom: 10px;
font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}
h1 {
font-family: "Bumble Bee", "Times New Roman", Georgia, Serif;
}
And your follow-up questions:
Q. I would like to use a font such as "Bumble bee," for example. How can I use
@font-face
to make that font available on the user's computer?
Note that I don't know what the name of your Bumble Bee font or file is, so adjust accordingly, and that the font-face declaration should precede (come before) your use of it, as I've shown above.
Q. Can I still use the other
@font-face
typeface "GestaRegular" as well? Can I use both in the same stylesheet?
Just list them together as I've shown in my example. There is no reason you can't declare both. All that @font-face
does is instruct the browser to download and make a font-family available. See: http://iliadraznin.com/2009/07/css3-font-face-multiple-weights
declare @cur cursor
declare @idx int
declare @Approval_No varchar(50)
declare @ReqNo varchar(100)
declare @M_Id varchar(100)
declare @Mail_ID varchar(100)
declare @temp table
(
val varchar(100)
)
declare @temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare @slice varchar(8000)
declare @String varchar(100)
--set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(',',@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
--select @slice
insert into @temp values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
-- select distinct(val) from @temp
SET @cur = CURSOR FOR select distinct(val) from @temp
--open cursor
OPEN @cur
--fetchng id into variable
FETCH NEXT
FROM @cur into @Approval_No
--
--loop still the end
while @@FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No
insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)
FETCH NEXT
FROM @cur into @Approval_No
end
--close cursor
CLOSE @cur
select * from @tem
In addition to VonC's answer, you could tweak it to your liking even further.
After fetching from the remote branch, you would still have to merge the commits. I would replace
$ git fetch upstream
with
$ git pull upstream master
since git pull is essentially git fetch + git merge.
Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do
pgrep -x PROCESS_NAME
-x Require an exact match of the process name, or argument list if -f is given. The default is to match any substring.
This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.
pop()
method will pop the last value out. But the problem is that you will lose the last value in the array
Check out http://www.odata.org/
It defines the MERGE method, so in your case it would be something like this:
MERGE /customer/123
<customer>
<status>DISABLED</status>
</customer>
Only the status
property is updated and the other values are preserved.
Using indexOf(it doesn’t work with IE8).
if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
// found
}
To support IE8, you could implement Mozilla’s indexOf.
if (!Array.prototype.indexOf) {
// indexOf polyfill code here
}
Regular Expressions via String.prototype.match (docs).
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
}
The colon actually exists in conjunction with ?
int minVal = (a < b) ? a : b;
is equivalent to:
int minval;
if(a < b){ minval = a;}
else{ minval = b; }
Also in the for each loop:
for(Node n : List l){ ... }
literally:
for(Node n = l.head; n.next != null; n = n.next)
I'm working on this right now as well. You should also add a datetime of the comment. You'll need this later when you want to sort by most recent.
Here are some of the db fields i'm using.
id (auto incremented)
name
email
text
datetime
approved
M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.
Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.
I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.
Singleton is, of course, an "anti-pattern" (assuming a definition of a static with variable state).
If you want a fixed set of immutable value objects, then enums are the way to go. For a large, possibly open-ended set of values, you can use a Repository of some form - usually based on a Map
implementation. Of course, when you are dealing with statics be careful with threading (either synchronise sufficiently widely or use a ConcurrentMap
either checking that another thread hasn't beaten you or use some form of futures).
If creating a SSLSocketFactory
is not an option, just import the key into the JVM
Retrieve the public key:
$openssl s_client -connect dev-server:443
, then create a file dev-server.pem that looks like
-----BEGIN CERTIFICATE-----
lklkkkllklklklklllkllklkl
lklkkkllklklklklllkllklkl
lklkkkllklk....
-----END CERTIFICATE-----
Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem
.
Password: changeit
Restart JVM
You need to do a couple of things to use the library:
Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2
Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.
Add it in database migrations, that way everyone gets it as they update. Handle all of your logic in the ruby/rails code, so you never have to mess with explicit ID settings.
I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.
If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.
Here is how to do it in Linq:
List<Employee> listA = new List<Employee>();
List<Employee> listB = new List<Employee>();
listA.Add(new Employee() { Id = 1, Name = "Bill" });
listA.Add(new Employee() { Id = 2, Name = "Ted" });
listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
listB.Add(new Employee() { Id = 3, Name = "Jim" });
var identicalQuery = from employeeA in listA
join employeeB in listB on employeeA.Id equals employeeB.Id
select new { EmployeeA = employeeA, EmployeeB = employeeB };
foreach (var queryResult in identicalQuery)
{
Console.WriteLine(queryResult.EmployeeA.Name);
Console.WriteLine(queryResult.EmployeeB.Name);
}
Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW
I'm sure one of the pedants will come up with a better answer shortly, but the main difference is speed and size.
Stack
Dramatically faster to allocate. It is done in O(1) since it is allocated when setting up the stack frame so it is essentially free. The drawback is that if you run out of stack space you are boned. You can adjust the stack size, but IIRC you have ~2MB to play with. Also, as soon as you exit the function everything on the stack is cleared. So it can be problematic to refer to it later. (Pointers to stack allocated objects leads to bugs.)
Heap
Dramatically slower to allocate. But you have GB to play with, and point to.
Garbage Collector
The garbage collector is some code that runs in the background and frees memory. When you allocate memory on the heap it is very easy to forget to free it, which is known as a memory leak. Over time, the memory your application consumes grows and grows until it crashes. Having a garbage collector periodically free the memory you no longer need helps eliminate this class of bugs. Of course this comes at a price, as the garbage collector slows things down.
You may need an extra "/"
<a href="file:///server/directory/file.xlsx">Click me!</a>
Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.
Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.
To figure out how big the display really is, check out GetSystemMetrics.
VistaDB has an express version which is free to use and is syntax and driver compatible with SQL Server. VistaDB is a single file and only requires their driver .dll to work in your asp.net or winforms project.
Since it is syntax and datasource compatible you can upgrade to SQL Server if needed.
from their site:
VistaDB is a fully managed and typesafe ASP.NET and WinForms applications using C#, VB.NET and other CLR-compliant languages.
Since the introduction of go.mod , I think both local and external package management becomes easier. Using go.mod, it is possible to have go project outside the GOPATH as well.
Create a folder demoproject and run following command to generate go.mod file
go mod init demoproject
I have a project structure like below inside the demoproject directory.
+-- go.mod
+-- src
+-- main.go
+-- model
+-- model.go
For the demo purpose, insert the following code in the model.go file.
package model
type Employee struct {
Id int32
FirstName string
LastName string
BadgeNumber int32
}
In main.go, I imported Employee model by referencing to "demoproject/src/model"
package main
import (
"demoproject/src/model"
"fmt"
)
func main() {
fmt.Printf("Main Function")
var employee = model.Employee{
Id: 1,
FirstName: "First name",
LastName: "Last Name",
BadgeNumber: 1000,
}
fmt.Printf(employee.FirstName)
}
Just run go get
command inside the project directory.
For example:
go get -u google.golang.org/grpc
It should include module dependency in the go.mod file
module demoproject
go 1.13
require (
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect
golang.org/x/text v0.3.2 // indirect
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150 // indirect
google.golang.org/grpc v1.26.0 // indirect
)
Update: This supports only with UWP - Windows Community Toolkit
There is a much easier way now. You can use the RssParser class. The sample code is given below.
public async void ParseRSS()
{
string feed = null;
using (var client = new HttpClient())
{
try
{
feed = await client.GetStringAsync("https://visualstudiomagazine.com/rss-feeds/news.aspx");
}
catch { }
}
if (feed != null)
{
var parser = new RssParser();
var rss = parser.Parse(feed);
foreach (var element in rss)
{
Console.WriteLine($"Title: {element.Title}");
Console.WriteLine($"Summary: {element.Summary}");
}
}
}
For non-UWP use the Syndication from the namespace System.ServiceModel.Syndication
as others suggested.
public static IEnumerable <FeedItem> GetLatestFivePosts() {
var reader = XmlReader.Create("https://sibeeshpassion.com/feed/");
var feed = SyndicationFeed.Load(reader);
reader.Close();
return (from itm in feed.Items select new FeedItem {
Title = itm.Title.Text, Link = itm.Id
}).ToList().Take(5);
}
public class FeedItem {
public string Title {
get;
set;
}
public string Link {
get;
set;
}
}
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $
represents the jQuery Function, and is actually a shorthand alias for jQuery
. (Unlike in most languages, the $
symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
In Python3.6, the StringIO
and cStringIO
modules are gone, you should use io.StringIO
instead.So you should do this like the first answer:
import sys
from io import StringIO
old_stdout = sys.stdout
old_stderr = sys.stderr
my_stdout = sys.stdout = StringIO()
my_stderr = sys.stderr = StringIO()
# blah blah lots of code ...
sys.stdout = self.old_stdout
sys.stderr = self.old_stderr
// if you want to see the value of redirect output, be sure the std output is turn back
print(my_stdout.getvalue())
print(my_stderr.getvalue())
my_stdout.close()
my_stderr.close()
In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.
If you want to see only the date of a tag you'd do:
git show -s --format=%ci <mytagname>^{commit}
which gives: 2013-11-06 13:22:37 +0100
Or do:
git show -s --format=%ct <mytagname>^{commit}
which gives UNIX timestamp: 1383740557
https://stackoverflow.com/a/48531811/9609776
This is ok but do not split the updateResources into different versions, just use the solution below (kotlin). Key is in "Configuration(context.resources.configuration)" it makes deep copy.
100% solution for API 21+. I have not tested for lower ones, but should work.
private fun updateResources(context: Context, language: String): Context {
return Configuration(context.resources.configuration).run {
Locale.setDefault(Locale(language).also { locale ->
setLocale(locale)
}).let {
context.createConfigurationContext(this)
}
}
}
If you get Cannot read property 'fn' of undefined, the problem may be you loading libraries in wrong order.
For example:
You should load bootstrap.js first and then load bootstrap.js libraries.
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
Easiest way is to provide the process id.
gdb -p `pidof your_running_program_name`
Please get the full list of option in man gdb
command.
In case there are multiple process for the same program running, then the following command will list the processes.
ps -C program -o pid h
<number>
Then the output process id (number) can be used as argument to gdb.
gdb -p <process id>
create view view_clients_credit_usage as
select client_id, sum(credits_used) as credits_used
from credit_usage
group by client_id
create view view_credit_status as
select
credit_orders.client_id,
sum(credit_orders.number_of_credits) as purchased,
ifnull(t1.credits_used,0) as used
from credit_orders
left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
where credit_orders.payment_status='Paid'
group by credit_orders.client_id)
Here's quite a good example of how you can get caught out from not declaring local variables with var
:
<script>
one();
function one()
{
for (i = 0;i < 10;i++)
{
two();
alert(i);
}
}
function two()
{
i = 1;
}
</script>
(i
is reset at every iteration of the loop, as it's not declared locally in the for
loop but globally) eventually resulting in infinite loop
Following code uses a third-party ZIP component from Rebex:
// add content of the local directory C:\Data\
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist)
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");
Or if you want to add more folders without need to open and close archive multiple times:
using Rebex.IO.Compression;
...
// open the ZIP archive from an existing file
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);
// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");
// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");
// close the archive
zip.Close(ArchiveSaveAction.Auto);
You can download the ZIP component here.
Using a free, LGPL licensed SharpZipLib is a common alternative.
Disclaimer: I work for Rebex
If you need the path
and thedomain
for each cookie, which get_dict()
is not exposes, you can parse the cookies manually, for instance:
[
{'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
for c in session.cookies
]
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
For a list of IP addresses on *nix systems,
import subprocess
co = subprocess.Popen(['ifconfig'], stdout = subprocess.PIPE)
ifconfig = co.stdout.read()
ip_regex = re.compile('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-5][0-9]|[01]?[0-9][0-9]?))')
[match[0] for match in ip_regex.findall(ifconfig, re.MULTILINE)]
Though it's a bit late for this answer, I thought someone else may find it useful :-)
PS : It'll return Broadcast addresses and Netmask as well.
Instead of including your js
file extension in index.html
, you can include it in .angular-cli-json
file.
These are the steps I followed to get this working:
js
file in assets/js
.angular-cli.json
- add the file path under scripts:
[../app/assets/js/test.js]
js
file.Declare at the top where you want to import the files as
declare const Test:any;
After this you can access its functions as for example Test.add()
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
In Laravel 4 & 5 (up to 5.7), you can use str_limit
, which limits the number of characters in a string.
While in Laravel 5.8 up, you can use the Str::limit
helper.
//For Laravel 4 to Laravel 5.5
{{ str_limit($string, $limit = 150, $end = '...') }}
//For Laravel 5.5 upwards
{{ \Illuminate\Support\Str::limit($string, 150, $end='...') }}
For more Laravel helper functions http://laravel.com/docs/helpers#strings
A minor modification to the above recursive generator solution in variadic flavor:
def product_args(*args):
if args:
for a in args[0]:
for prod in product_args(*args[1:]) if args[1:] else ((),):
yield (a,) + prod
And of course a wrapper which makes it work exactly the same as that solution:
def product2(ar_list):
"""
>>> list(product(()))
[()]
>>> list(product2(()))
[]
"""
return product_args(*ar_list)
with one trade-off: it checks if recursion should break upon each outer loop, and one gain: no yield upon empty call, e.g.product(())
, which I suppose would be semantically more correct (see the doctest).
Regarding list comprehension: the mathematical definition applies to an arbitrary number of arguments, while list comprehension could only deal with a known number of them.
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
Using awk
echo $STRING | awk -v N=$N '{print $N}'
Test
% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three
request.getParameterValues("select2")
returns an array of all submitted values.
I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:
This method also may be tried by the readers.
Long shot but try setting the proxy to "" (empty string) that should override any proxy settings according to the man page.
Using psql's meta-command \c or \connect [ dbname [ username ] [ host ] [ port ] ] | conninfo
(see documentation).
Example: \c MyDatabase
Note that the \c
and \connect
meta-commands are case-sensitive.
Try the Magnific Popup, it's responsive and weights just around 3KB.
I know this is a very old question but I post this solution in case it helps somebody. I recently met this problem and google led me here. The answer here helps me to understand the problem but there are still issues due to my parameter combination. What eventually solves my problem is curl to C# converter. It is a very powerful tool and supports most of the parameters for Curl. The code it generates is almost immediately runnable.
It is a unary "+" operator which yields a numeric expression. It would be the same as d*1
, I believe.
You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.
As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
If you are entering text into the label beforehand, you can do this.
I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.
Here is a script that does exactly what you want
https://github.com/UziTech/js-date-format
var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
The simplest way to read each line of a file into a bash
array is this:
IFS=$'\n' read -d '' -r -a lines < /etc/passwd
Now just index in to the array lines
to retrieve each line, e.g.
printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"
# all lines
echo "${lines[@]}"
I got same problem trying to compile "clean install" using a Lowend 512Mb ram VPS and good CPU. Run OutOfMemory and killed script repeatly.
I used export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=350m"
and worked.
Still getting some other compiling failure because is the first time i need Maven, but OutOfMemory problem has gone.
I successfully installed Font Awesome using their CDN and javascript include (as described on this page). Then I tried to copy the HTML and CSS to some legacy pages and suddenly I saw empty square boxes instead of the icons.
I saw Daniel's answer (above) and because my legacy CSS file was huge (and years old) I suspected that was the issue. However when I looked in Chrome DevTools it really looked like Font Awesome was loaded:
I was expecting to see the font in strikeout if there was an issue... However I had really exhausted all my options so I checked the Computed Styles and saw clearly that the Font Awesome font was definitely not being used. (See the Rendered font at the bottom)
My legacy CSS file was a mess and I preferred not to touch it, so I cheated by doing this - please don't tell anyone :)
<a class="nav-link fa fa-instagram" style="font-family:FontAwesome;" href="//www.instagram.com/xxxx/" target="_blank"></a>
Also to note, when I upgraded from Font Awesome version 4.7.0 to version 5.4.1 this issue went away! I used this setup guide and this HTML
<a class="nav-link" href="//www.instagram.com/xxxx/" target="_blank"><i class="fab fa-instagram"></i></a>
This helped for me for connecting to AWS MYSQL(RDS) from python 3.x based lambda function and loading into a pandas DataFrame
import json
import boto3
import pymysql
import pandas as pd
user = 'username'
password = 'XXXXXXX'
client = boto3.client('rds')
def lambda_handler(event, context):
conn = pymysql.connect(host='xxx.xxxxus-west-2.rds.amazonaws.com', port=3306, user=user, passwd=password, db='database name', connect_timeout=5)
df= pd.read_sql('select * from TableName limit 10',con=conn)
print(df)
# TODO implement
#return {
# 'statusCode': 200,
# 'df': df
#}
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
The answers so far are obviously great for the reproducibility part. This is merely to clarify that a reproducible example cannot and should not be the sole component of a question. Don't forget to explain what you want it to look like and the contours of your problem, not just how you have attempted to get there so far. Code is not enough; you need words also.
Here's a reproducible example of what to avoid doing (drawn from a real example, names changed to protect the innocent):
The following is sample data and part of function I have trouble with.
code
code
code
code
code (40 or so lines of it)
How can I achieve this ?
Here's a brief one for getting a specified number of tweets from your timeline. It basically does the same thing as the other examples, only with less code.
Just fill in the keys and adjust $count
to your liking:
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$count = '10';
$oauth = array('count' => $count,
'oauth_consumer_key' => '[CONSUMER KEY]',
'oauth_nonce' => md5(mt_rand()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => '[ACCESS TOKEN]',
'oauth_version' => '1.0');
$oauth['oauth_signature'] = base64_encode(hash_hmac('sha1', 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', array_map(function ($v, $k) { return $k . '=' . $v; }, $oauth, array_keys($oauth)))), '[CONSUMER SECRET]&[ACCESS TOKEN SECRET]', true));
$twitterData = json_decode(file_get_contents($url . '?count=' . $count, false, stream_context_create(array('http' => array('method' => 'GET',
'header' => 'Authorization: OAuth '
. implode(', ', array_map(function ($v, $k) { return $k . '="' . rawurlencode($v) . '"'; }, $oauth, array_keys($oauth))))))));
This one uses anonymous functions and file_get_contents
instead of the cURL library. Note the use of an MD5 hashed nonce. Everyone seems to be going along with the time()
nonce, however, most examples on the web concerning OAuth use some kind of encrypted string (like this one: http://www.sitepoint.com/understanding-oauth-1/). This makes more sense to me too.
Further note: you need PHP 5.3+ for the anonymous functions (in case your server/computer is in some cold war cave and you can't upgrade it).
Yes, take a look at this thread which talks about the differences between platforms.
How to detect right-click event for Mac OS
BUTTON3
is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.
You can use jQuery:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
In OSX El Capitan update when you do this:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
it throws an error like
ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted
So to avoid this, what you can do is first locate libmysqlclient.18.dylib
using the command
User$ locate libmysqlclient.18.dylib
In my case it returned /usr/local/mysql-5.5.24-osx10.5-x86_64/lib/libmysqlclient.18.dylib
So instead of usr/lib/
we will create symlink to usr/local/lib/
like this :
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
More details : https://forums.developer.apple.com/thread/7935
Attach an event listener to a parent element that fires when an event occurs on a child element.
Event PropagationWhen an event moves through the DOM from child to a parent element, that's called Event Propagation, because the event propagates, or moves through the DOM.
In this example, an event (onclick) from a button gets passed to the parent paragraph.
$(document).ready(function() {_x000D_
_x000D_
$(".spoiler span").hide();_x000D_
_x000D_
/* add event onclick on parent (.spoiler) and delegate its event to child (button) */_x000D_
$(".spoiler").on( "click", "button", function() {_x000D_
_x000D_
$(".spoiler button").hide(); _x000D_
_x000D_
$(".spoiler span").show();_x000D_
_x000D_
} );_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="spoiler">_x000D_
<span>Hello World</span>_x000D_
<button>Click Me</button>_x000D_
</p>
_x000D_
- How do I find Android SDK on my machine? Or prove to myself it's not there?
When you install Android studio, it allows you to choose if you want to download SDK or not
- If it's not there how do I install it?
you can get SDK from here http://developer.android.com/sdk/index.html
- How do I change PATH to include Android SDK?
THIS CAN BE A QUICK FIX FOR ECLIPSE
When I was trying to create array list it gave error that array list cannot be resolved to type and something about "parametrised type are only in level 1.5"
Only I did was I tried to import java.util.ArrayList;
And that error went away.
When I applied the unique index below:
CREATE UNIQUE NONCLUSTERED INDEX idx_badgeid_notnull
ON employee(badgeid)
WHERE badgeid IS NOT NULL;
every non null update and insert failed with the error below:
UPDATE failed because the following SET options have incorrect settings: 'ARITHABORT'.
I found this on MSDN
SET ARITHABORT must be ON when you are creating or changing indexes on computed columns or indexed views. If SET ARITHABORT is OFF, CREATE, UPDATE, INSERT, and DELETE statements on tables with indexes on computed columns or indexed views will fail.
So to get this to work correctly I did this
Right click [Database]-->Properties-->Options-->Other Options-->Misscellaneous-->Arithmetic Abort Enabled -->true
I believe it is possible to set this option in code using
ALTER DATABASE "DBNAME" SET ARITHABORT ON
but i have not tested this
Running "Valgrind" can:
1) Help Identify Memory Leaks - show you how many memory leaks you have, and point out to the lines in the code where the leaked memory was allocated.
2) Point out wrong attempts to free memory (e.g. improper call of delete
)
Instructions for using "Valgrind"
1) Get valgrind here.
2) Compile your code with -g
flag
3) In your shell run:
valgrind --leak-check=yes myprog arg1 arg2
Where "myprog" is your compiled program and arg1
, arg2
your programme's arguments.
4) The result is a list of calls to malloc
/new
that did not have subsequent calls to free delete.
For example:
==4230== at 0x1B977DD0: malloc (vg_replace_malloc.c:136)
==4230== by 0x804990F: main (example.c:6)
Tells you in which line the malloc
(that was not freed) was called.
As Pointed out by others, make sure that for every new
/malloc
call, you have a subsequent delete
/free
call.
you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder
P.S dont forget to add Console.Readline() after this code snippet else console will not appear.
TextWriter tw = new StreamWriter("filename.txt");
String text = "Hello";
tw.WriteLine(text);
tw.Close();
TextReader tr = new StreamReader("filename.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
You can specify both max post size and max file size limit in php.ini
post_max_size = 64M
upload_max_filesize = 64M
Just another idea:
>>> bin(6)[2:].zfill(8)
'00000110'
Shorter way via string interpolation (Python 3.6+):
>>> f'{6:08b}'
'00000110'
Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES
in your case
forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"
the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway
I am trying to contribute with another solution for the single insertion problem with the pre-9.5 versions of PostgreSQL. The idea is simply to try to perform first the insertion, and in case the record is already present, to update it:
do $$
begin
insert into testtable(id, somedata) values(2,'Joe');
exception when unique_violation then
update testtable set somedata = 'Joe' where id = 2;
end $$;
Note that this solution can be applied only if there are no deletions of rows of the table.
I do not know about the efficiency of this solution, but it seems to me reasonable enough.
In MYSQL server version: 5.0.27 i tried this and it worked fine for me check in your version
ALTER TABLE carmake
MODIFY `country` ENUM('Japan', 'USA', 'England', 'Australia', 'Germany', 'France', 'Italy', 'Spain', 'Czech Republic', 'China', 'South Korea', 'India', 'Sweden', 'Malaysia');
Android 4.4 (KitKat) and higher devices have a shell utility for recording the Android device screen. Connect a device in developer/debug mode running KitKat with the adb utility over USB and then type the following:
adb shell screenrecord /sdcard/movie.mp4
(Press Ctrl-C to stop)
adb pull /sdcard/movie.mp4
Screen recording is limited to a maximum of 3 minutes.
Reference: https://developer.android.com/studio/command-line/adb.html#screenrecord
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
Edit:
@t1m0thy's answer is more elegant than mine, better follow his advices.
Also, nice link proposed by @aldemarcalazans in the comments: https://davidwalsh.name/html5-buttons.
Original answer:
Use <a />
when you need a link (the a of anchor). Use <button />
when you need a button.
That said, if you really need to expand an <a />
, add the CSS attribute display: block;
on it. You'll then be able to specify a width and/or a height (i.e. as if it were a <div />
).
If you're not too worried in accuracy after days, you can simply do the maths
function timeSince(when) { // this ignores months
var obj = {};
obj._milliseconds = (new Date()).valueOf() - when.valueOf();
obj.milliseconds = obj._milliseconds % 1000;
obj._seconds = (obj._milliseconds - obj.milliseconds) / 1000;
obj.seconds = obj._seconds % 60;
obj._minutes = (obj._seconds - obj.seconds) / 60;
obj.minutes = obj._minutes % 60;
obj._hours = (obj._minutes - obj.minutes) / 60;
obj.hours = obj._hours % 24;
obj._days = (obj._hours - obj.hours) / 24;
obj.days = obj._days % 365;
// finally
obj.years = (obj._days - obj.days) / 365;
return obj;
}
then timeSince(pastDate);
and use the properties as you like.
Otherwise you can use .getUTC*
to calculate it, but note it may be slightly slower to calculate
function timeSince(then) {
var now = new Date(), obj = {};
obj.milliseconds = now.getUTCMilliseconds() - then.getUTCMilliseconds();
obj.seconds = now.getUTCSeconds() - then.getUTCSeconds();
obj.minutes = now.getUTCMinutes() - then.getUTCMinutes();
obj.hours = now.getUTCHours() - then.getUTCHours();
obj.days = now.getUTCDate() - then.getUTCDate();
obj.months = now.getUTCMonth() - then.getUTCMonth();
obj.years = now.getUTCFullYear() - then.getUTCFullYear();
// fix negatives
if (obj.milliseconds < 0) --obj.seconds, obj.milliseconds = (obj.milliseconds + 1000) % 1000;
if (obj.seconds < 0) --obj.minutes, obj.seconds = (obj.seconds + 60) % 60;
if (obj.minutes < 0) --obj.hours, obj.minutes = (obj.minutes + 60) % 60;
if (obj.hours < 0) --obj.days, obj.hours = (obj.hours + 24) % 24;
if (obj.days < 0) { // months have different lengths
--obj.months;
now.setUTCMonth(now.getUTCMonth() + 1);
now.setUTCDate(0);
obj.days = (obj.days + now.getUTCDate()) % now.getUTCDate();
}
if (obj.months < 0) --obj.years, obj.months = (obj.months + 12) % 12;
return obj;
}
I vote for IB(Interactive Brokers). I've used them in the past as was quite happy. Pinnacle Capital Markets trading also has an API (pcmtrading.com) but I haven't used them.
Interactive Brokers:
https://www.interactivebrokers.com/en/?f=%2Fen%2Fsoftware%2Fibapi.php
Pinnacle Capital Markets:
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
strTheseAreInvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
if (!dir.Exists)
dir.Create();
return true;
}
I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.
In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.
[May be this should have been a comment. Sorry that I don't have enough reputation yet.]
I like using a package.json file in the root of your app folder.
Here is one I use
nvm use v0.6.4
npm install
Use innerText
/textContent
:
var el = document.getElementById('*spaM4');
console.log(el.innerText || el.textContent);
Fiddle: http://jsfiddle.net/NeTgC/2/
…or a shorter try:
library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
the picked table is the longest one on the page
tables[[which.max(n.rows)]]
Its so simple! You can go with your button click event, I used it with a button property Name: "btnClearImage"
// Note 1a:
// after clearing the picture box
// you can also disable clear button
// by inserting follwoing one line of code:
btnClearImage.Enabled = false
// Note 1b:
// you should set your button Enabled property
// to "False"
// after that you will need to Insert
// the following line to concerned event or button
// that load your image into picturebox1
// code line is as follows:
btnClearImage.Enabled = true;
1) Setting the first Panel:
JFrame frame=new JFrame();
frame.getContentPane().add(new JPanel());
2)Replacing the panel:
frame.getContentPane().removeAll();
frame.getContentPane().add(new JPanel());
Also notice that you must do this in the Event's Thread, to ensure this use the SwingUtilities.invokeLater or the SwingWorker
You cannot clear the browser history. It belongs to the user, not the developer. Also have a look at the MDN documentation.
Update: The link you were posting all over does not actually clear your browser history. It just prevents using the back button.
In Mysql, you can not update one table by subquery the same table.
You can separate the query in two parts, or do
UPDATE TABLE_A AS A INNER JOIN TABLE_A AS B ON A.field1 = B.field1 SET field2 = ?
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
Although using const
to define functions seems like a hack, but it comes with some great advantages that make it superior (in my opinion)
It makes the function immutable, so you don't have to worry about that function being changed by some other piece of code.
You can use fat arrow syntax, which is shorter & cleaner.
Using arrow functions takes care of this
binding for you.
example with function
// define a function_x000D_
function add(x, y) { return x + y; }_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// oops, someone mutated your function_x000D_
add = function (x, y) { return x - y; };_x000D_
_x000D_
// now this is not what you expected_x000D_
console.log(add(1, 2)); // -1
_x000D_
same example with const
// define a function (wow! that is 8 chars shorter)_x000D_
const add = (x, y) => x + y;_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// someone tries to mutate the function_x000D_
add = (x, y) => x - y; // Uncaught TypeError: Assignment to constant variable._x000D_
// the intruder fails and your function remains unchanged
_x000D_
There are tons of ways to do this and it's important to pick the right one. Probably one of the biggest architectural decisions lies on how the model code will be shared or accessed throughout the app.
I wrote a blog post about this a while back: Sharing Model Code. Here's a brief summary:
One approach is to share pointers to the model objects between view controllers.
Since prepare for segue is the most common here is an example:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var next = segue.destinationViewController as NextViewController
next.dataSource = dataSource
}
Another approach is to handle a screen full of data at a time and instead of coupling the view controllers to each other couple each view controller to single data source that they can get to independently.
The most common way I've seen this done is a singleton instance. So if your singleton object was DataAccess
you could do the following in the viewDidLoad method of UIViewController:
func viewDidLoad() {
super.viewDidLoad()
var data = dataAccess.requestData()
}
There are addition tools that also help pass along data:
The nice thing about Core Data is that it has inverse relationships. So if you want to just give a NotesViewController the notes object you can because it'll have an inverse relationship to something else like the notebook. If you need data on the notebook in the NotesViewController you can walk back up the object graph by doing the following:
let notebookName = note.notebook.name
Read more about this in my blog post: Sharing Model Code
var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]
This will return undefined if the array is empty and this will not change the value of the array.
The most compact version of a command to remove all untagged images is:
docker rmi $(docker images | grep "^<none>" | awk '{print $"3"}')
Functional Interfaces: An interface is called a functional interface if it has a single abstract method irrespective of the number of default or static methods. Functional Interface are use for lamda expression. Runnable
, Callable
, Comparable
, Comparator
are few examples of Functional
Interface.
KeyNotes:
@FunctionalInterface
is used(Optional).@FunctionalInterface
annotation is
used).This thread talks more in detail about what benefit functional Interface gives over anonymous class and how to use them.
Extended - to provide more details based on some comments
The error
Error TS2306: File 'test.ts' is not a module.
Comes from the fact described here http://exploringjs.com/es6/ch_modules.html
17. Modules
This chapter explains how the built-in modules work in ECMAScript 6.
17.1 OverviewIn ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.
17.1.1 Multiple named exports
There can be multiple named exports:
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } ...
17.1.2 Single default export
There can be a single default export. For example, a function:
//------ myFunc.js ------ export default function () { ··· } // no semicolon!
Based on the above we need the export
, as a part of the test.js file. Let's adjust the content of it like this:
// test.js - exporting es6
export module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
export class OtherClass {
getName(): string {
return 'name';
}
}
}
And now we can import it with these thre ways:
import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";
And we can consume imported stuff like this:
var a1: app1.App.SomeClass = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();
var b1: app2.App.SomeClass = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();
var c1: App.SomeClass = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();
and call the method to see it in action:
console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())
Original part is trying to help to reduce the amount of complexity in usage of the namespace
I would really strongly suggest to check this Q & A:
Let me cite the first sentence:
Do not use "namespaces" in external modules.
Don't do this.
Seriously. Stop.
...
In this case, we just do not need module
inside of test.ts
. This could be the content of it adjusted test.ts
:
export class SomeClass
{
getName(): string
{
return 'name';
}
}
Read more here
In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.
The
export =
syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.
we can later consume it like this:
import App = require('./test');
var sc: App.SomeClass = new App.SomeClass();
sc.getName();
Read more here:
In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.
The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.
The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).
we can use the spring-core
dependency;
boolean result = FileSystemUtils.deleteRecursively(file);
In my case the culprit was the lone opening <?php
tag in the last line of the file. Apparently it works on some configurations with no problems but causes problems on others.
Try to delete the import line import com.your.package.name.app.R
, then, any resource calls such as mView= (View) mView.findViewById(R.id.resource_name);
will highlight the 'R' with an error, a 'Quick fix' will prompt you to import R, and there will be at least two options:
Select the R corresponding to your package name, and you should be good to go. Hope that helps.
I found that the only way to get the cursor to effectively reset its style back to what it had prior to being changed to the wait style was to set the original style in a style sheet or in style tags at the start of the page, set the class of the object in question to the name of the style. Then after your wait period, you set the cursor style back to an empty string, NOT "default" and it reverts back to its original value as set in your style tags or style sheet. Setting it to "default" after the wait period only changes the cursor style for every element to the style called "default" which is a pointer. It doesn't change it back to its former value.
There are two conditions to make this work. First you must set the style in a style sheet or in the header of the page with style tags, NOT as an inline style and second is to reset its style by setting the wait style back to an empty string.
Thanks guys for help. From your suggestions i reached a solution like this.
new LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints:
BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(children: [
// remaining stuffs
]),
),
);
},
)
I came across this trying to add labels o some vertical radio boxes. I had to do this:
<%: Html.RadioButton("RadioGroup1", "Yes") %><label style="display:inline-block;padding-top:2px;">Yes</label><br />
<%: Html.RadioButton("RadioGroup1", "No") %><label style="display:inline-block;padding-top:3px;">No</label><br />
<%: Html.RadioButton("RadioGroup1", "Maybe") %><label style="display:inline-block;padding-top:4px;">Maybe</label><br />
This gets them to display properly, where the label is centered on the radio button, though I had to increment the top padding with each line, as you can see. The code isn't pretty, but the result is.
Try this:
$('#contra').focusout(function (){
$('#btnPassword').focus();
});
I think but I am not sure : the for
loop takes two operations for checking and incrementing values. foreach
loads the data in memory then it will iterate every values.
You can pass new value like this
setExampleState({...exampleState, masterField2: {
fieldOne: "c",
fieldTwo: {
fieldTwoOne: "d",
fieldTwoTwo: "e"
}
},
}})
If you want the column as string values, then:
SELECT id, name, CASE WHEN hide = 0 THEN 'false' ELSE 'true' END AS hide
FROM anonymous_table
If the DBMS supports BOOLEAN, you can use instead:
SELECT id, name, CASE WHEN hide = 0 THEN false ELSE true END AS hide
FROM anonymous_table
That's the same except that the quotes around the names false
and true
were removed.
You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well
Yes you are right. There is no built in mechanism for automatically updation of Android Studio. You have to manually download it and configure it.
If you need to insert into a specific position in the array, you can do this:
case ADD_ITEM :
return {
...state,
arr: [
...state.arr.slice(0, action.pos),
action.newItem,
...state.arr.slice(action.pos),
],
}
CSRF protection
TYPES OF CSRF USAGE
IN FORM
<form>
@csrf
</form>
or
<input type="hidden" name="token" value="{{ form_token() }}" />
META TAG
<meta name="csrf-token" content="{{ csrf_token() }}">
AJAX
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
SESSION
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
MIDDLEWARE
App\Providers\RouteServiceProvider
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}
$("#id").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url: ,
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{
alert(test);
}
}
});
MVC 5 is already built into Visual Studios 2013.
Open a new project, on the left make sure you are under Templates > Visual C# > Web not Templates > Visual C# > Web > Visual Studios 2012.
Important: Now look near the top of the new project dialog box and select .NET 4.5 or higher. Once under web and the proper framework is selected click ASP.NET Web Application in the middle pane. Click OK
This will bring you to a page where you can select MVC as the project and start the wizard.
Procedures and functions are both subroutines the only difference between them is that a procedure returns multiple (or at least can do) values whereas a function can only return one value (this is why function notation is used in maths as usually only one value is found at one given time) although some programming languages do not follow these rules this is their true definitions
Two types module import and export.
type 1 (module.js):
// module like a webpack config
const development = {
// ...
};
const production = {
// ...
};
// export multi
module.exports = [development, production];
// export single
// module.exports = development;
type 1 (main.js):
// import module like a webpack config
const { development, production } = require("./path/to/module");
type 2 (module.js):
// module function no param
const module1 = () => {
// ...
};
// module function with param
const module2 = (param1, param2) => {
// ...
};
// export module
module.exports = {
module1,
module2
}
type 2 (main.js):
// import module function
const { module1, module2 } = require("./path/to/module");
How to use import module?
const importModule = {
...development,
// ...production,
// ...module1,
...module2("param1", "param2"),
};
Under the covers there will be some form of URL loading request. You can't load images or any other content via this method from a local file system.
Your image needs to be loaded via a web server, so accessed via a proper http URL.
I wrote this snippet, that I've been using for handling this exact case.
It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.
<script type='text/javascript'>
window.onhashchange=hashTriggerTab;
window.onload=hashTriggerTab;
function hashTriggerTab(){
var current_hash=window.location.hash;
if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
if(current_hash!=''){
var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
if(trigger)trigger.click();
}
}
</script>
With that in place, you could link both on the same page, like:
<a href='#tabId'>Link Any Tab</a>
Or from external page like:
<a href='newpage.php#tabId'>Link From External</a>
The original Netscape <blink>
had an 80% duty cycle. This comes pretty close, although the real <blink>
only affects text:
.blink {_x000D_
animation: blink-animation 1s steps(5, start) infinite;_x000D_
-webkit-animation: blink-animation 1s steps(5, start) infinite;_x000D_
}_x000D_
@keyframes blink-animation {_x000D_
to {_x000D_
visibility: hidden;_x000D_
}_x000D_
}_x000D_
@-webkit-keyframes blink-animation {_x000D_
to {_x000D_
visibility: hidden;_x000D_
}_x000D_
}
_x000D_
This is <span class="blink">blinking</span> text.
_x000D_
You can find more info about Keyframe Animations here.
It seems like str_shuffle would be a good use for this. Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);
All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems
in the NotifyCollectionChangedEventArgs
object.
this is the perfect ObservableCollection
.
public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
#region Constructors
public ObservableCollectionEX() : base()
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(IEnumerable<T> c) : base(c)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(List<T> l) : base(l)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
#endregion
public new void Clear()
{
foreach (var item in this)
if (item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
base.Clear();
}
private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (var item in e.OldItems)
if (item != null && item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
if (e.NewItems != null)
foreach (var item in e.NewItems)
if (item != null && item is INotifyPropertyChanged i)
{
i.PropertyChanged -= Element_PropertyChanged;
i.PropertyChanged += Element_PropertyChanged;
}
}
}
private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);
public ListedItemPropertyChangedEventHandler ItemPropertyChanged;
}
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
It seems that I don't have to set the focus to any other elements. On a Windows Phone 7 application, I've been using the Focus method to unset the Focus of a Textbox.
Giving the following command will set the focus to nothing:
void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Focus();
}
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx
It worked for me, but I don't know why didn't it work for you :/
You can also get the page count using
$im->getNumberImages();
Then you can can create thumbs of all the pages using a loop, eg.
'file.pdf['.$x.']'
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);
In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyActivity2"
android:label="@string/title_activity_my_activity2"
android:theme="@style/myDialog"
>
</activity>
</application>
styles.xml example
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
<!-- Customize your theme here. -->
</style>
<style name="myDialog" parent="android:Theme.Dialog">
</style>
In parent you set actualy the theme
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
I am using Eclipse. I have resolved this problem by the following:
You will not get any this kind of error.
<button type="button" href="location.href='#/nameOfState'">Title on button</button>
Even more simple... (note the single quotes around the address)
i got the same problem so tried so many things but finally this is the solution.
import time
print (time.strftime("%d/%m/%Y"))
BeanUtils will only copy public fields and is a bit slow. Instead go with getter and setter methods.
public Object loadData (RideHotelsService object_a) throws Exception{
Method[] gettersAndSetters = object_a.getClass().getMethods();
for (int i = 0; i < gettersAndSetters.length; i++) {
String methodName = gettersAndSetters[i].getName();
try{
if(methodName.startsWith("get")){
this.getClass().getMethod(methodName.replaceFirst("get", "set") , gettersAndSetters[i].getReturnType() ).invoke(this, gettersAndSetters[i].invoke(object_a, null));
}else if(methodName.startsWith("is") ){
this.getClass().getMethod(methodName.replaceFirst("is", "set") , gettersAndSetters[i].getReturnType() ).invoke(this, gettersAndSetters[i].invoke(object_a, null));
}
}catch (NoSuchMethodException e) {
// TODO: handle exception
}catch (IllegalArgumentException e) {
// TODO: handle exception
}
}
return null;
}
another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:
UserZone = User.zones.through
# for a single zone
users_in_zone = User.objects.filter(
id__in=UserZone.objects.filter(zone=zone1).values('user'))
# for multiple zones
users_in_zones = User.objects.filter(
id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))
it would be nice if it didn't need the .values('user')
specified, but Django (version 3.0.7) seems to need it.
the above code will end up generating SQL that looks something like:
SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))
which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned
Extend WebViewClient and call onPageFinished() as follows:
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});
If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform
property:
.myclass {
text-transform: lowercase;
}
See https://developer.mozilla.org/en/CSS/text-transform for more info.
However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.
While ASP.NET MVC will allow you to have two actions with the same name, .NET won't allow you to have two methods with the same signature - i.e. the same name and parameters.
You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.
That said, if you're talking about a GET and a POST, this problem will likely go away, as the POST action will take more parameters than the GET and therefore be distinguishable.
So, you need either:
[HttpGet]
public ActionResult ActionName() {...}
[HttpPost, ActionName("ActionName")]
public ActionResult ActionNamePost() {...}
Or,
[HttpGet]
public ActionResult ActionName() {...}
[HttpPost]
public ActionResult ActionName(string aParameter) {...}
Well... I see that an answer was already accepted... but I think you should see another solutions anyway:
/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'
/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT
LEFT(tmp.UserId, 10) +
'/ ' +
STUFF(
( SELECT ', '+Alias
FROM @UserAliases
WHERE UserId = tmp.UserId
FOR XML PATH('')
)
, 1, 2, ''
) AS [UserId/Alias]
FROM tmp
/* -- OUTPUT
UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
*/
download jdk 8u221
$ wget -c --content-disposition "https://javadl.oracle.com/webapps/download/AutoDL?BundleId=239835_230deb18db3e4014bb8e3e8324f81b43"
$ old=$(ls -hat | grep jre | head -n1)
$ mv $old $(echo $old | awk -F"?" '{print $1}')
my blog 044-wget??jdk8u221
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
This should work, at least according to the Search Filter Syntax article on MSDN network.
The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.
You may also try separating the filter into two parts:
(|(displayName=*searchstring)(displayName=searchstring*))
One way is to use the Database property off the DbContext:
SqlParameter param1 = new SqlParameter("@firstName", "Frank");
SqlParameter param2 = new SqlParameter("@lastName", "Borland");
context.Database.ExecuteSqlCommand("sp_MyStoredProc @firstName, @lastName",
param1, param2);
EF5 definitely supports that.
From the MySQL reference manual:
By default, all log files are created in the data directory.
Check /var/lib/mysql
folder.
button {_x000D_
background: none!important;_x000D_
border: none;_x000D_
padding: 0!important;_x000D_
/*optional*/_x000D_
font-family: arial, sans-serif;_x000D_
/*input has OS specific font-family*/_x000D_
color: #069;_x000D_
text-decoration: underline;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<button> your button that looks like a link</button>
_x000D_
It's only necessary to prepare the string variable first and then convert it to the RegEx.
for example:
You want to add minLength
and MaxLength
with the variable to RegEx:
function getRegEx() {
const minLength = "5"; // for exapmle: min is 5
const maxLength = "12"; // for exapmle: man is 12
var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
regEx = new RegExp(regEx, "g"); // now we convert it to RegEx
return regEx; // In the end, we return the RegEx
}
now if you change value of MaxLength
or MinLength
, It will change in all RegExs.
Hope to be useful. Also sorry about my English.
Because this is a frequent viewed question, I want to mention that a PowerShell function should use approved verbs (Verb-Noun as the function name). The verb part of the name identifies the action that the cmdlet performs. The noun part of the name identifies the entity on which the action is performed. This rule simplifies the usage of your cmdlets for advanced PowerShell users.
Also, you can specify things like whether the parameter is mandatory and the position of the parameter:
function Test-Script
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$arg1,
[Parameter(Mandatory=$true, Position=1)]
[string]$arg2
)
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
To pass the parameter to the function you can either use the position:
Test-Script "Hello" "World"
Or you specify the parameter name:
Test-Script -arg1 "Hello" -arg2 "World"
You don't use parentheses like you do when you call a function within C#.
I would recommend to always pass the parameter names when using more than one parameter, since this is more readable.
ORA-03113: end-of-file on communication channel
Is the database letting you know that the network connection is no more. This could be because:
For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME
. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.
For 1) (network) speak to your network admin (connection could be unreliable)
For 2) Check the alert.log
for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.
Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)
A nifty trick I saw in a C answer to this question, just add a last element to the enum and use it to tell how many elements are in the enum:
enum MyType {
Type1,
Type2,
Type3,
NumberOfTypes
}
In the case where you're defining a start value other than 0, you can use NumberOfTypes - Type1 to ascertain the number of elements.
I'm unsure if this method would be faster than using Enum, and I'm also not sure if it would be considered the proper way to do this, since we have Enum to ascertain this information for us.
As astander has mentioned, you can do that with a UDF. However, for large sets using a scalar function (as oppoosed to a inline-table function) the performance will stink as the function is evaluated row-by-row. As an alternative, you could expose the same results via a stored procedure executing a fixed query with placeholders which substitutes in your parameter values.
(Here's a somewhat dated but still relevant article on row-by-row processing for scalar UDFs.)
Edit: comments re. degrading performance adjusted to make it clear this applies to scalar UDFs.
Here is one way you could do it...
find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"
This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-
List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();
It's a very cool library that saves you a tonne of time.
There are two reasons you might get this message:
%FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i
. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.Finally SQL Server 2016 will add Native JSON support!!
Ref:
Additional capabilities in SQL Server 2016 include:
- Additional security enhancements for Row-level Security and Dynamic Data Masking to round out our security investments with Always
Encrypted.- Improvements to AlwaysOn for more robust availability and disaster recovery with multiple synchronous replicas and secondary load
balancing.- Native JSON support to offer better performance and support for your many types of your data.
- SQL Server Enterprise Information Management (EIM) tools and Analysis Services get an upgrade in performance, usability and scalability.
- Faster hybrid backups, high availability and disaster recovery scenarios to backup and restore your on-premises databases to Azure
and place your SQL Server AlwaysOn secondaries in Azure.
Features blog post: http://blogs.msdn.com/b/jocapc/archive/2015/05/16/json-support-in-sql-server-2016.aspx
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.
Using _blank
will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).
I am using Spring 4.1.6 and Jackson FasterXML 2.1.4.
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<!-- ?????null??-->
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
this works at my applicationContext.xml configration
Here is a solution witch takes into account duplicate entries. It is written in javascript and assumes array is sorted. The solution runs in O(n) time and does not use any extra memory aside from variable.
var count_pairs = function(_arr,x) {
if(!x) x = 0;
var pairs = 0;
var i = 0;
var k = _arr.length-1;
if((k+1)<2) return pairs;
var halfX = x/2;
while(i<k) {
var curK = _arr[k];
var curI = _arr[i];
var pairsThisLoop = 0;
if(curK+curI==x) {
// if midpoint and equal find combinations
if(curK==curI) {
var comb = 1;
while(--k>=i) pairs+=(comb++);
break;
}
// count pair and k duplicates
pairsThisLoop++;
while(_arr[--k]==curK) pairsThisLoop++;
// add k side pairs to running total for every i side pair found
pairs+=pairsThisLoop;
while(_arr[++i]==curI) pairs+=pairsThisLoop;
} else {
// if we are at a mid point
if(curK==curI) break;
var distK = Math.abs(halfX-curK);
var distI = Math.abs(halfX-curI);
if(distI > distK) while(_arr[++i]==curI);
else while(_arr[--k]==curK);
}
}
return pairs;
}
I solved this during an interview for a large corporation. They took it but not me. So here it is for everyone.
Start at both side of the array and slowly work your way inwards making sure to count duplicates if they exist.
It only counts pairs but can be reworked to
Enjoy!
I know its already answered, but theres a better solution here use this code :
for ( Field f : context.getFields() ) {
if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
//DO String To JSON
}
/// And so on...
}
This way you can access variables from class without manually typing them..
Faster and better .. Hope this helps.
Cheers. :D
if($('#testElement').is(':visible')){
//what you want to do when is visible
}
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
I made it work with keyup.
$("#id input").trigger('keyup');
You may use MessageBox
if you want but it is recommended to use alert
(from JavaScript) instead.
If you want to use it you should write:
System.Windows.Forms.MessageBox.Show("Test");
Note that you must specify the namespace.
Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:
public class MainClass
{
public static void main(String args[])
{
System.out.println("Hello, World!");
//step1 : first create array of 10 elements that holds object addresses.
Emp[] employees = new Emp[10];
//step2 : now create objects in a loop.
for(int i=0; i<employees.length; i++){
employees[i] = new Emp(i+1);//this will call constructor.
}
}
}
class Emp{
int eno;
public Emp(int no){
eno = no;
System.out.println("emp constructor called..eno is.."+eno);
}
}
Use this:
Format(Now, "MMMM dd, yyyy")
More: Format Function
For Swift 3+ and Xcode 9+ Try using this
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionWidth = collectionView.bounds.width
return CGSize(width: collectionWidth/3, height: collectionWidth/3)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
You have to add extra parameter -g, which generates source level debug information. It will look like:
gcc -g prog.c
After that you can use gdb in common way.
Just set this extra line in catalina.bat
file
LINE NO AROUND: 143
set "CATALINA_OPTS=-Xms512m -Xmx512m"
And restart Tomcat service
Much longer solution, but accounts for the following scenarios:
Is the image taller than the bounding box
private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
{
//throw error if bouning box is to small
if (desiredWidth < 4 || desiredHeight < 4)
throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");
var original = Bitmap.FromFile(sourceImage.FullName);
//store image widths in variable for easier use
var oW = (decimal)original.Width;
var oH = (decimal)original.Height;
var dW = (decimal)desiredWidth;
var dH = (decimal)desiredHeight;
//check if image already fits
if (oW < dW && oH < dH)
return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
//check for double squares
if (oW == oH && dW == dH)
{
//image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
Bitmap square = new Bitmap(original, (int)dW, (int)dH);
original.Dispose();
return square;
}
//check original image is square
if (oW == oH)
{
//image is square, bounding box isn't. Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
int smallSide = (int)Math.Min(dW, dH);
Bitmap square = new Bitmap(original, smallSide, smallSide);
original.Dispose();
return square;
}
//not dealing with squares, figure out resizing within aspect ratios
if (oW > dW && oH > dH) //image is wider and taller than bounding box
{
var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
var nW = oW * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
else
{
if (oW > dW) //image is wider than bounding box
{
var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
var nW = oW * r; //downscale image by r to fit in the bounding box...
var nH = oH * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
else
{
//original image is taller than bounding box
var r = dH / oH;
var nH = oH * r;
var nW = oW * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
}
}
Mobile view: how to hide toggle navigation in bootstrap + dropdown + jquery + scrollto with navigation items that points to anchors/ids on the same page, one page template
The issue I was experimenting with any of the above solutions was that they are collapsing only the submenu items, while the navigation menu doesn't collapse.
So I did my thought.. and what can we observe? Well, every time we/the users click an scrollto link, we want the page to scroll to that position and contemporaneously, collapse the menu to restore the page view.
Well... why not to assign this job to the scrollto functions? Easy :-)
So in the two codes
// scroll to top action
$('.scroll-top').on('click', function(event) {
event.preventDefault();
$('html, body').animate({scrollTop:0}, 'slow');
and
// scroll function
function scrollToID(id, speed){
var offSet = 67;
var targetOffset = $(id).offset().top - offSet;
var mainNav = $('#main-nav');
$('html,body').animate({scrollTop:targetOffset}, speed);
if (mainNav.hasClass("open")) {
mainNav.css("height", "1px").removeClass("in").addClass("collapse");
mainNav.removeClass("open");
}
I've just added the same command in both the functions
if($('.navbar-toggle').css('display') !='none'){
$(".navbar-toggle").trigger( "click" );
}
(kudos to one of the above contributors)
like this (the same should be added to both the scrolls)
$('.scroll-top').on('click', function(event) {
event.preventDefault();
$('html, body').animate({scrollTop:0}, 'slow');
if($('.navbar-toggle').css('display') !='none'){
$(".navbar-toggle").trigger( "click" );
}
});
if you wanna see it in action just check it out recupero dati da NAS
I also experienced this error when working with CMake:
No CMAKE_C_COMPILER could be found.
No CMAKE_CXX_COMPILER could be found.
The 'warning' box in the MSDN library article Visual C++ in Visual Studio 2015 gave me the help that I needed.
Visual Studio 2015 doesn't come with C++ installed by default. So, creating a new C++ project will prompt you to download the necessary C++ components.
Add a $event
to the ng-click
, for example:
<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>
Then the jQuery.Event
was passed to the callback:
Here is the example works fine in oracle
select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
To stop a for
loop early in JavaScript, you use break
:
var remSize = [],
szString,
remData,
remIndex,
i;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}
If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex
(to find the entry's index) or Array#find
(to find the entry itself), both of which can be shimmed/polyfilled:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});
Array#find
:
var remSize = [],
szString,
remData,
remEntry;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});
Array#findIndex
stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1
if the callback never returns a truthy value. Array#find
also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined
if the callback never returns a truthy value).
If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some
function on arrays, which calls a callback until the callback returns a truthy value:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
if (entry.size === remData.size) {
remIndex = index;
return true; // <== Equivalent of break for `Array#some`
}
});
If you're using jQuery, you can use jQuery.each
to loop through an array; that would look like this:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});
SELECT *
FROM tbl
WHERE myDate BETWEEN #date one# AND #date two#;
If you are using pwsh (powershell core), you can try
(docker ps --format='{{json .}}' | ConvertFrom-Json).Mounts
also you can see both container name and Mounts as below
docker ps --format='{{json .}}' | ConvertFrom-Json | select Names,Mounts
As the output is converted as json ,you can get any properties it has.
Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:
public function up()
{
Schema::create('trip_table', function (Blueprint $table) {
$table->increments('trip_id')->unsigned();
$table->time('est_start');
$table->time('est_end');
$table->time('act_start')->nullable();
$table->time('act_end')->nullable();
$table->date('Trip_Date');
$table->integer('Starting_Miles')->nullable();
$table->integer('Ending_Miles')->nullable();
$table->string('Bus_id')->nullable();
$table->string('Event');
$table->string('Desc')->nullable();
$table->string('Destination');
$table->string('Departure_location');
$table->text('Drivers_Comment')->nullable();
$table->string('Requester')->nullable();
$table->integer('driver_id')->nullable();
$table->timestamps();
});
}
The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
You should set android:button="@null"
instead of "null"
.
You were soo close!
You could also use wp_list_categories();
wp_list_categories( array('taxonomy' => 'product_cat', 'title_li' => '') );
It might be the Unmerged paths that cause
error: Merging is not possible because you have unmerged files.
If so, try:
git status
if it says
You have unmerged paths.
do as suggested: either resolve conflicts and then commit or abort the merge entirely with
git merge --abort
You might also see files listed under Unmerged paths, which you can resolve by doing
git rm <file>
Just search for "ab" in the string then negate the result:
!/ab/.test("bamboo"); // true
!/ab/.test("baobab"); // false
It seems easier and should be faster too.
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List
in an EditorTemplate.
I have a model like this:
public class Foo
{
public string FooName { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarName { get; set; }
}
And this is my main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.EditorFor(m => m.Bars)
And this is my Bar EditorTemplate (Bar.cshtml)
@model List<Bar>
<div class="some-style">
@foreach (var item in Model)
{
<label>@item.BarName</label>
}
</div>
And I got this error:
The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]
The reason for this error is that EditorFor
already iterates the List
for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.
This is how I fixed this problem:
Brought the styles outside of the editor template, and into the main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<div class="some-style">
@Html.EditorFor(m => m.Bars)
</div>
And changed the EditorTemplate (Bar.cshtml) to this:
@model Bar
<label>@Model.BarName</label>
The problem with system.gc, is that the JVM already automatically allocates time to the garbage collector based on memory usage.
However, if you are, for instance, working in a very memory limited condition, like a mobile device, System.gc allows you to manually allocate more time towards this garbage collection, but at the cost of cpu time (but, as you said, you aren't that concerned about performance issues of gc).
Best practice would probably be to only use it where you might be doing large amounts of deallocation (like flushing a large array).
All considered, since you are simply concerned about memory usage, feel free to call gc, or, better yet, see if it makes much of a memory difference in your case, and then decide.
As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml
Usage is straightforward:
HtmlConverter.ConvertToPdf(
new FileInfo(@"Path\to\Html\File.html"),
new FileInfo(@"Path\to\Pdf\File.pdf")
);
Method has many more overloads.
Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths
method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
Take a look at this example from The Linux Documentation Project:
3.6 Sample: stderr and stdout 2 file
This will place every output of a program to a file. This is suitable sometimes for cron entries, if you want a command to pass in absolute silence.
rm -f $(find / -name core) &> /dev/null
That said, you can use this simple redirection:
/path/to/command &>/dev/null
Try Like This: For SQL SERVER 2008+
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyColumnaName%'
Or
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%MyName%'
Or Something Like This:
SELECT name
FROM sys.tables
WHERE OBJECT_ID IN ( SELECT id
FROM syscolumns
WHERE name like '%COlName%' )
Looks like things have changed lately. In XCode 7.2 the following approach works:
override func viewDidLoad() {
super.viewDidLoad()
let swipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
swipeGesture.direction = [.Down, .Up]
self.view.addGestureRecognizer(swipeGesture)
}
func handleSwipe(sender: UISwipeGestureRecognizer) {
print(sender.direction)
}
Tested in Simulator on iOS 8.4 and 9.2 and on actual device on 9.2.
Or, using mlcollard's handy extension here:
let swipeGesture = UISwipeGestureRecognizer() {
print("Gesture recognized !")
}
swipeGesture.direction = [.Down, .Up]
self.view.addGestureRecognizer(swipeGesture)
If you need to remove just trailing whitespace, you could use str.rstrip()
, which should be slightly more efficient than str.strip()
:
>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']
In the header file write it with extern
.
And at the global scope of one of the c files declare it without extern
.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model {
use SoftDeletes;
protected $table = 'posts';
// ...
}
When soft deleting a model, it is not actually removed from your database. Instead, a
deleted_at
timestamp is set on the record. To enable soft deletes for a model, specify thesoftDelete
property on the model (Documentation).
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required
class Post extends Eloquent {
use SoftDeletingTrait;
protected $table = 'posts';
// ...
}
For example (Using a posts
table and Post
model):
class Post extends Eloquent {
protected $table = 'posts';
protected $softDelete = true;
// ...
}
To add a deleted_at column to your table, you may use the
softDeletes
method from a migration:
For example (Migration class' up
method for posts
table) :
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table)
{
$table->increments('id');
// more fields
$table->softDeletes(); // <-- This will add a deleted_at field
$table->timeStamps();
});
}
Now, when you call the delete
method on the model, the deleted_at
column will be set to the current timestamp
. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete
a model you may use:
$model = Contents::find( $id );
$model->delete();
Deleted (soft) models are identified by the timestamp
and if deleted_at
field is NULL
then it's not deleted and using the restore
method actually makes the deleted_at
field NULL
. To permanently delete a model you may use forceDelete
method.
Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.
You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).
Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.
Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.
Hope this helps someone, I've found expressions in ng-class to be very useful!
HTML
<ul>
<li ng-repeat="person in people"
data-ng-class="{'active-selection': person.id == activeClass}">
<a data-ng-click="selectPerson(person.id)">
{{person.name}}
</a>
</li>
</ul>
JS
app.controller('MainCtrl', function($scope) {
$scope.people = [{
id: "1",
name: "John",
}, {
id: "2",
name: "Lucy"
}, {
id: "3",
name: "Mark"
}, {
id: "4",
name: "Sam"
}];
$scope.selectPerson = function(id) {
$scope.activeClass = id;
console.log(id);
};
});
CSS:
.active-selection {
background-color: #eee;
}
If you scale 1600x900
to 1280x720
you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Then you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720
to 1600x900
you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)
Does anyone see any reason why not to do this?
mystring.Select(Convert.ToByte).ToArray()
Queue is an Interface not a class.
Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways
Sharing host network --net=host:
docker run -it --net=host myimage
Using docker's ip address, which is usually 172.17.0.1. You can check it by calling ifconfig command and grabbing inet addr of docker interface
user@ubuntu:~$ ifconfig
docker0 Link encap:Ethernet HWaddr 02:42:a4:a2:b2:f1
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link
Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.
docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage
NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here:
Edit postgresql.conf to listen on all addresses. By default it will point to localhost.
listen_addresses = '*'
Edit pg_hba.conf to allow connections from all addresses. Add on the last line:
host all all 0.0.0.0/0 md5
IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.
Because when the script executes the browser has not yet parsed the <body>
, so it does not know that there is an element with the specified id.
Try this instead:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = (function () {
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('Dhoor shala!');
};
});
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
Note that you may as well use addEventListener
instead of window.onload = ...
to make that function only execute after the whole document has been parsed.
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
I have this function for this case ..
Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean
c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
Select Case Mid(c, x, 1)
Case ":": bNum = True
Case " ": Exit For
Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
End Select
Next
GetValue = val(nRet)
End Function
To fill cell BC .. (assumed that you check cell A1)
Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
The href is probably generated in a javascript function. For example with jQuery:
$(function() {
$('a.view').attr('href', 'http://www.google.com');
});
Maybe you like to check the links below:
While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, 'xyc"foo');return false;">Test</a>
The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..
The fastest way I know to generate a new-line character in Java is: String.format("%n")
Of course you can put whatever you want around the %n
like:
String.format("line1%nline2")
Or even if you have a lot of lines:
String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")
I have used something like the following in C++ code before:
#include <sstream>
int main()
{
char* str = "1234";
std::stringstream s_str( str );
int i;
s_str >> i;
}
You can specify multiple patterns in an array.
select-string VendorEnquiry,Failed C:\Logs
This works with -notmatch as well:
select-string -notmatch VendorEnquiry,Failed C:\Logs
Just a shot in the dark(since you did not share the compiler
initialization code with us): the way you retrieve the compiler
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE
.
There are two ways you can count the number of rows.
$query = "SELECT count(*) as total from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_ASSOC);
echo $row['total']; // This will return you a number of rows.
Or second way is
$query = "SELECT field1, field2 from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_NUM);
echo $rows[0]; // This will return you a number of rows as well.
If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ"));
That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.
In my computer, I get this code works.It's a little different from Daimon's answer.
@SqlResultSetMapping(_x000D_
name="groupDetailsMapping",_x000D_
classes={_x000D_
@ConstructorResult(_x000D_
targetClass=GroupDetails.class,_x000D_
columns={_x000D_
@ColumnResult(name="GROUP_ID",type=Integer.class),_x000D_
@ColumnResult(name="USER_ID",type=Integer.class)_x000D_
}_x000D_
)_x000D_
}_x000D_
)_x000D_
_x000D_
@NamedNativeQuery(name="User.getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
_x000D_
Just reset your simulator by clicking Simulator-> Reset Contents and Settings..
You can also get this error message on its own, without any stack trace or any further error message.
In this case you need to make sure your Android manifest is configured correctly (including any manifest merging happening from a library and any activity that would come from a library), and pay particular attention to the first activity displayed in your application in your manifest files.
Update your Eclipse ADT Plugin to 22.0 or higher, then go to File | Export
Go to Android now then click on Generate Gradle build files
, then it would generate gradle file for you.
Select your project you want to export
Click on finish now
In Android Studio, close any projects currently open. You should see the Welcome to Android Studio window.
Click Import Project.
Locate the project you exported from Eclipse, expand it, select it and click OK.
Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll
instance method:
List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);
I simply just add e(fx)clipse in eclipse marketplace. Easy and simple
Simply instantiate an anonymous function:
var foo = new function () {
this.a = 5;
this.b = 6;
this.c = this.a + this.b;
};
Use finish
like this:
Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish(); //Kill the activity from which you will go to next activity
startActivity(i);
FLAG_ACTIVITY_NO_HISTORY
you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.
To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY
read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY
For chart.js V2 (beta), use:
var options = {
scales: {
yAxes: [{
display: true,
ticks: {
suggestedMin: 0, // minimum will be 0, unless there is a lower value.
// OR //
beginAtZero: true // minimum value will be 0.
}
}]
}
};
See chart.js documentation on linear axes configuration for more details.