<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.
What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:
header('Content-Type: application/json; charset=utf-8');
The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.
In Spring 5, or maybe in earlier versions, there is MediaType
class. It has already correct line, if you want to follow DRY:
public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
So I use this set of controller-related annotations:
@RestController
@RequestMapping(value = "my/api/url", produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
// ... Methods here
}
It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.
There is a method in php-intl extension:
locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE'])
If you want to take screenshot from fragment
than follow this:
Override onCreateView()
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
mView = view;
}
Logic for taking screenshot:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View view = mView.findViewById(R.id.scrollView1);
shareScreenShotM(view, (NestedScrollView) view);
}
method shareScreenShotM)()
:
public void shareScreenShotM(View view, NestedScrollView scrollView){
bm = takeScreenShot(view,scrollView); //method to take screenshot
File file = savePic(bm); // method to save screenshot in phone.
}
method takeScreenShot():
public Bitmap takeScreenShot(View u, NestedScrollView z){
u.setDrawingCacheEnabled(true);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Log.d("yoheight",""+ totalHeight);
Log.d("yowidth",""+ totalWidth);
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
u.destroyDrawingCache();
return b;
}
method savePic():
public static File savePic(Bitmap bm){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File sdCardDirectory = new File(Environment.getExternalStorageDirectory() + "/Foldername");
if (!sdCardDirectory.exists()) {
sdCardDirectory.mkdirs();
}
// File file = new File(dir, fileName);
try {
file = new File(sdCardDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
file.createNewFile();
new FileOutputStream(file).write(bytes.toByteArray());
Log.d("Fabsolute", "File Saved::--->" + file.getAbsolutePath());
Log.d("Sabsolute", "File Saved::--->" + sdCardDirectory.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
For activity you can simply use View v1 = getWindow().getDecorView().getRootView();
instead of mView
@Guiseppe:
I have no idea of Grobs etc whatsoever, but I hacked together a solution for two plots, should be possible to extend to arbitrary number but its not in a sexy function:
plots <- list(p1, p2)
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
tmp <- arrangeGrob(p1 + theme(legend.position = "none"), p2 + theme(legend.position = "none"), layout_matrix = matrix(c(1, 2), nrow = 1))
grid.arrange(tmp, legend, ncol = 1, heights = unit.c(unit(1, "npc") - lheight, lheight))
I know this is really old, but I'm posting my solution anyways since google finds this thread.
background-image: url('./imagefolder/image.jpg');
That is what I do. Two dots means drill back one directory closer to root ".." while one "." should mean start where you are at as if it were root. I was having similar issues but adding that fixed it for me. You can even leave the "." in it when uploading to your host because it should work fine so long as your directory setup is exactly the same.
This will replace backslashes with forward slashes in the string:
source = source.replace('\\','/');
This runs fine on Java 1.6
~ % javac RemoveListElementDemo.java
~ % java RemoveListElementDemo
~ % cat RemoveListElementDemo.java
import java.util.*;
public class RemoveListElementDemo {
private static final List<Integer> integerList;
static {
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
}
public static void remove(Integer remove) {
for(Integer integer : integerList) {
if(integer.equals(remove)) {
integerList.remove(integer);
}
}
}
public static void main(String... args) {
remove(Integer.valueOf(2));
Integer remove = Integer.valueOf(3);
for(Integer integer : integerList) {
if(integer.equals(remove)) {
integerList.remove(integer);
}
}
}
}
~ %
Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.
You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.
I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.
This article offers a fairly comprehensive explanation:
"Comparing the Timer Classes in the .NET Framework Class Library" - also available as a .chm file
The specific difference appears to be that System.Timers.Timer
is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject
property, whereas System.Threading.Timer
is ironically not thread-safe out-of-the-box.
I don't believe that there is a difference between the two as it pertains to how small your intervals can be.
function getTodaysTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const startOfDay = currentTimeStamp - (currentTimeStamp % 86400);_x000D_
return { startOfDay, endOfDay: startOfDay + 86400 - 1 };_x000D_
}_x000D_
_x000D_
// starts from sunday_x000D_
function getThisWeeksTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const currentDay = new Date(currentTimeStamp * 1000);_x000D_
const startOfWeek = currentTimeStamp - (currentDay.getDay() * 86400) - (currentTimeStamp % 86400);_x000D_
return { startOfWeek, endOfWeek: startOfWeek + 7 * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
function getThisMonthsTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const currentDay = new Date(currentTimeStamp * 1000);_x000D_
const startOfMonth = currentTimeStamp - ((currentDay.getDate() - 1) * 86400) - (currentTimeStamp % 86400);_x000D_
const currentMonth = currentDay.getMonth() + 1;_x000D_
let daysInMonth = 0;_x000D_
if (currentMonth === 2) daysInMonth = 28;_x000D_
else if ([1, 3, 5, 7, 8, 10, 12].includes(currentMonth)) daysInMonth = 31;_x000D_
else daysInMonth = 30;_x000D_
return { startOfMonth, endOfMonth: startOfMonth + daysInMonth * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
console.log(getTodaysTimeStamp());_x000D_
console.log(getThisWeeksTimeStamp());_x000D_
console.log(getThisMonthsTimeStamp());
_x000D_
def capitalizeWords(s):
return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)
re.sub
can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match
object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.
A longer version of the same thing:
WORD_RE = re.compile(r'\w+')
def capitalizeMatch(m):
return m.group(0).capitalize()
def capitalizeWords(s):
return WORD_RE.sub(capitalizeMatch, s)
This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.
You can get it using the :selected
selector, like this:
$("#my_select").change(function() {
var id = $(this).children(":selected").attr("id");
});
Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".
One can use this to pretty print a request, like so:
import requests
req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()
def pretty_print_POST(req):
"""
At this point it is completely built and ready
to be fired; it is "prepared".
However pay attention at the formatting used in
this function because it is programmed to be pretty
printed and may differ from the actual request.
"""
print('{}\n{}\r\n{}\r\n\r\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
pretty_print_POST(prepared)
which produces:
-----------START-----------
POST http://stackoverflow.com/
Content-Length: 7
X-Custom: Test
a=1&b=2
Then you can send the actual request with this:
s = requests.Session()
s.send(prepared)
These links are to the latest documentation available, so they might change in content: Advanced - Prepared requests and API - Lower level classes
you should check ios UITableViewDataSourcePrefetching.
class ViewController: UIViewController {
@IBOutlet weak var mytableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
mytableview.prefetchDataSource = self
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
print("prefetchdRowsAtIndexpath \(indexPaths)")
}
func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
print("cancelPrefetchingForRowsAtIndexpath \(indexPaths)")
}
}
I used to virtus
. Really powerful tool, allows to create a dynamic Ruby structure structure based on your specified classes. Easy DSL, possible to create objects from ruby hashes, there is strict mode. Check it out.
This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.
If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.
If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.
var resizeTimer;
$( window ).resize(function() {
if(resizeTimer){
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function() {
//your code here
resizeTimer = null;
}, 200);
});
This worked for what I was trying to do in chrome. This won't fire the callback until 200ms after last resize event.
If you just want to initialize outside of any method then use the initializer blocks :
import java.util.ArrayList;
public class Test {
private ArrayList<String> symbolsPresent = new ArrayList<String>();
// All you need is this block.
{
symbolsPresent = new ArrayList<String>();
symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");
}
public ArrayList<String> getSymbolsPresent() {
return symbolsPresent;
}
public void setSymbolsPresent(ArrayList<String> symbolsPresent) {
this.symbolsPresent = symbolsPresent;
}
public static void main(String args[]) {
Test t = new Test();
System.out.println("Symbols Present is" + t.symbolsPresent);
}
}
For a smooth slideup:
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").slideUp(500);
});
$(document).ready(function() {_x000D_
$("#success-alert").hide();_x000D_
$("#myWish").click(function showAlert() {_x000D_
$("#success-alert").fadeTo(2000, 500).slideUp(500, function() {_x000D_
$("#success-alert").slideUp(500);_x000D_
});_x000D_
});_x000D_
});
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<div class="product-options">_x000D_
<a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>_x000D_
<a href="" class="btn btn-mini"> Purchase </a>_x000D_
</div>_x000D_
<div class="alert alert-success" id="success-alert">_x000D_
<button type="button" class="close" data-dismiss="alert">x</button>_x000D_
<strong>Success! </strong> Product have added to your wishlist._x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
_x000D_
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
You can use aggregate to calculate the means:
means<-aggregate(df,by=list(df$gender),mean)
Group.1 tea coke beer water gender
1 1 87.70171 27.24834 24.27099 37.24007 1
2 2 24.73330 25.27344 25.64657 24.34669 2
Get rid of the Group.1 column
means<-means[,2:length(means)]
Then you have reformat the data to be in long format:
library(reshape2)
means.long<-melt(means,id.vars="gender")
gender variable value
1 1 tea 87.70171
2 2 tea 24.73330
3 1 coke 27.24834
4 2 coke 25.27344
5 1 beer 24.27099
6 2 beer 25.64657
7 1 water 37.24007
8 2 water 24.34669
Finally, you can use ggplot2 to create your plot:
library(ggplot2)
ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+
geom_bar(stat="identity",position="dodge")+
scale_fill_discrete(name="Gender",
breaks=c(1, 2),
labels=c("Male", "Female"))+
xlab("Beverage")+ylab("Mean Percentage")
You could use a HTML DTD, and the generic XML parsing libraries.
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
get
the value/array of the JsonNode
put
on the parent.Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
I ran into this same problem and ended up using a JQuery solution to make it seem like a class can inherit other classes.
<script>
$(function(){
$(".composite").addClass("something else");
});
</script>
This will find all elements with the class "composite" and add the classes "something" and "else" to the elements. So something like <div class="composite">...</div>
will end up like so:
<div class="composite something else">...</div>
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
This functionality can also be added using JavaScript. Carto.net has an example:
http://old.carto.net/papers/svg/textFlow/
Something else that also might be useful to are you are editable text areas:
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
Yes, it's a standard practice to commit package-lock.json
.
The main reason for committing package-lock.json
is that everyone in the project is on the same package version.
Pros:
Cons:
npm install
won't make sure that everyone in the project is on the same package version. npm ci
will help with this.
Try this code:
Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
If you want to use a stable version of your preferred Laravel version of choice, use:
composer create-project --prefer-dist laravel/laravel project-name "5.5.*"
That will pick out the most recent or best update of version 5.5.* (5.5.28)
StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
"||");
while(st.hasMoreTokens()){
System.out.println(st.nextElement());
}
Answer will print
1 1 Abdul-Jabbar Karim 1996 1974
I know I am late, but stumped into the question, and based on ThomasH's answer:
for i in range(4): print "i equals 3" if i==3 else None
output: None None None i equals 3
I propose to update as:
for i in range(4): print("i equals 3") if i==3 else print('', end='')
output: i equals 3
Note, I am in python3 and had to use two print commands. pass after else won't work. Wanted to just comment on ThomasH's answer, but can't because I don't have enough reputation yet.
I went back to jquery-2.2.4.min.js and it works.
Tip: You can also use this method to track certificates that are due to expire soon. This can save your bacon if you discover a cert that is about to expire and can get it fixed in time. Good also for third party companies - for us this is DHL / FedEx. DHL just let a cert expire which is screwing us up 3 days before Thanksgiving. Fortunately I'm around to fix it ... this time!
private static DateTime? _nextCertWarning;
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
if (error == SslPolicyErrors.None)
{
var cert2 = cert as X509Certificate2;
if (cert2 != null)
{
// If cert expires within 2 days send an alert every 2 hours
if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
{
if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
{
_nextCertWarning = DateTime.Now.AddHours(2);
ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString()); // this is my own function
}
}
}
return true;
}
else
{
switch (cert.GetCertHashString())
{
// Machine certs - SELF SIGNED
case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":
return true;
default:
ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
return false;
}
}
}
<input type="text" style="width:50px;"/>
try table.Rows.add(row);
after your for
statement.
Run it every three days...
0 0 */3 * *
How about that?
If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.
if (((date('j') - 1) % 3))
exit();
or, as @mario points out, you can use date('k') to get the day of the year instead of doing it based on the day of the month.
I find that document.getElementById('textbox-id').readOnly=true
sometimes doesn't work reliably.
Instead, try:
document.getElementById('textbox-id').setAttribute('readonly', 'readonly')
and
document.getElementById('textbox-id').removeAttribute('readonly')
.
A little verbose but it seems to be dependable.
<input [ngModel]="item.value | useMyPipeToFormatThatValue"
(ngModelChange)="item.value=$event" name="inputField" type="text" />
The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)]
actually encompasses. []
is one-way binding syntax and ()
is event binding syntax. When used together - [()]
Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.
The reason you cannot use [()]
with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.
See Angular Template Syntax for more info.
ImageIcon
s. For a single image, I would think about making a custom subclass of JPanel
and overriding its paintComponent
method to draw the image.Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
And note that since Python types are only checked at runtime you can have code like:
if True:
x = 2
y = 4
else:
x = "One"
y = "Two"
print(x + y)
But I'm having trouble thinking of other ways in which the code would operate without an error because of type issues.
Here is how I fixed the problem in Windows. I was trying to install the CLI for Angular.
Turn off firewall and antivirus protections.
Right click the nodejs folder (under Program Files), select Properties (scroll all the way down), click the Security tab, and click all items in the ALLOW column (for All System Packages and any user or group that allows you to add the “allow” checkmark).
Click the Windows icon. Type cmd. Right click the top result and select Run as Administrator. A command window results.
Type npm cache clean. If there is an error, close log files or anything open and rerun.
Type npm install -g @angular/cli (Or whatever npm install command you are using)
Check the installation by typing ng –version (Or whatever you need to verify your install)
Good luck! Note: If you are still having problems, check the Path in Environmental Variables. (To access: Control Panel ? System and Security ? System ? Advanced system settings ? Environment variables.) My path variable included the following: C:\Users\Michele\AppData\Roaming\npm
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
If a
is a prime then the while x:
in your code will run forever, since x
will remain True
.
So why is that while
there?
I think you wanted to end the for loop when you found a factor, but didn't know how, so you added that while since it has a condition. So here is how you do it:
def is_prime(a):
x = True
for i in range(2, a):
if a%i == 0:
x = False
break # ends the for loop
# no else block because it does nothing ...
if x:
print "prime"
else:
print "not prime"
You use the modf
function:
double integral;
double fractional = modf(some_double, &integral);
You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.
I have created a custom class AlwaysMarqueTextView
public class AlwaysMarqueeTextView extends TextView
{
protected boolean a;
public AlwaysMarqueeTextView(Context context)
{
super(context);
a = false;
}
public AlwaysMarqueeTextView(Context context, AttributeSet attributeset)
{
super(context, attributeset);
a = false;
}
public AlwaysMarqueeTextView(Context context, AttributeSet attributeset, int i)
{
super(context, attributeset, i);
a = false;
}
public boolean isFocused()
{
return a || super.isFocused();
}
public void setAlwaysMarquee(boolean flag)
{
setSelected(flag);
setSingleLine(flag);
if(flag)
setEllipsize(TruncateAt.MARQUEE);
a = flag;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
{
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused)
{
if(focused)
super.onWindowFocusChanged(focused);
}
}
And you can startMarquee when desire.. like
//textView.setSelected(true); No need of Selection..
textview.setAlwaysMarquee(true);
Hive Vs Pig-
Hive is as SQL interface which allows sql savvy users or Other tools like Tableu/Microstrategy/any other tool or language that has sql interface..
PIG is more like a ETL pipeline..with step by step commands like declaring variables, looping, iterating , conditional statements etc.
I prefer writing Pig scripts over hive QL when I want to write complex step by step logic. When I am comfortable writing a single sql for pulling the data i want i use Hive. for hive you will need to define table before querying(as you do in RDBMS)
The purpose of both are different but under the hood, both do the same, convert to map reduce programs.Also the Apache open source community is add more and more features to both there projects
Out of curiosity, why don't you just use the url for the said folder?
Assuming that the folder never changes location, that would be the easiest way to do it.
My preferred approach, which uses data
attributes to hold the state of the number:
<input type='number' step='0.01'/>
// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)
// react to keys
el.addEventListener('onkeyup', ev => {
// user cleared field
if (!ev.target.value) ev.target.dataset.val = ''
// non num input
if (isNaN(ev.key)) {
// deleting
if (ev.keyCode == 8)
ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)
// num input
} else ev.target.dataset.val += ev.key
ev.target.value = parseFloat(ev.target.dataset.val) / 100
})
I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.
var xhr = new XMLHttpRequest()
xhr.open('POST', 'https://mywebsite.com', true)
xhr.withCredentials = true
xhr.onreadystatechange = function() {
if (xhr.readyState === 2) {// do something}
}
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(json)
Hopefully this helps anyone else with the same issues.
\z mytable
from psql gives you all the grants from a table, but you'd then have to split it up by individual user.
If the selection changes, make sure to clear the other checks first. al la...
$('input[name="' + value.id + '"]').attr('checked', false);_x000D_
$('input[name="' + value.id + '"][value="' + thing[value.prop] + '"]').attr('checked', true);_x000D_
_x000D_
You can't read individual integers in a single line separately using BufferedReader
as you do using Scanner
class.
Although, you can do something like this in regard to your query :
import java.io.*;
class Test
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
for(int i=0;i<t;i++)
{
String str=br.readLine();
String num[]=br.readLine().split(" ");
int num1=Integer.parseInt(num[0]);
int num2=Integer.parseInt(num[1]);
//rest of your code
}
}
}
I hope this will help you.
Just add two attributes to the parent view of editText.
android:focusable="true"
android:focusableInTouchMode="true"
you could also use $location.$$search.yourparameter
While in Java a long
is always 64 bits, in C++ this depends on computer architecture and operating system. For example, a long
is 64 bits on Linux and 32 bits on Windows (this was done to keep backwards-compatability, allowing 32-bit programs to compile on 64-bit Windows without any changes).
It is considered good C++ style to avoid short int long ...
and instead use:
std::int8_t # exactly 8 bits
std::int16_t # exactly 16 bits
std::int32_t # exactly 32 bits
std::int64_t # exactly 64 bits
std::size_t # can hold all possible object sizes, used for indexing
These (int*_t
) can be used after including the <cstdint>
header. size_t
is in <stdlib.h>
.
As pointed out by Edric, it's just a matter of adding the google web fonts link in your document's head now, like so:
<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet">
And then adding the correct class to output the icon of a particular theme.
<i class="material-icons">donut_small</i>
<i class="material-icons-outlined">donut_small</i>
<i class="material-icons-two-tone">donut_small</i>
<i class="material-icons-round">donut_small</i>
<i class="material-icons-sharp">donut_small</i>
The color of the icons can be changed using CSS as well.
Note: the Two-tone theme icons are a bit glitchy at present.
Here's the most recent list of 16 outline icons that work with the regular Material-icons Webfont, using the _outline suffix (tested and confirmed).
(As found on the material-design-icons github page. Search for: "_outline_24px.svg")
<i class="material-icons">help_outline</i>
<i class="material-icons">label_outline</i>
<i class="material-icons">mail_outline</i>
<i class="material-icons">info_outline</i>
<i class="material-icons">lock_outline</i>
<i class="material-icons">lightbulb_outline</i>
<i class="material-icons">play_circle_outline</i>
<i class="material-icons">error_outline</i>
<i class="material-icons">add_circle_outline</i>
<i class="material-icons">people_outline</i>
<i class="material-icons">person_outline</i>
<i class="material-icons">pause_circle_outline</i>
<i class="material-icons">chat_bubble_outline</i>
<i class="material-icons">remove_circle_outline</i>
<i class="material-icons">check_box_outline_blank</i>
<i class="material-icons">pie_chart_outlined</i>
Note that pie_chart needs to be "pie_chart_outlined" and not outline.
As of today (July 19, 2018), a little over 2 months since the new icons themes were introduced, there is No Way to include these icons using an inline tag <i class="material-icons"></i>
.
+Martin has pointed out that there's an issue raised on Github regarding the same: https://github.com/google/material-design-icons/issues/773
So, until Google comes up with a solution for this, I've started using a hack to include these new icon themes in my development environment before downloading the appropriate icons as SVG or PNG. And I thought I'd share it with you all.
IMPORTANT: Do not use this on a production environment as each of the included CSS files from Google are over 1MB in size.
Google uses these stylesheets to showcase the icons on their demo page:
Outline:
<link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/outline.css">
Rounded:
<link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/round.css">
Two-Tone:
<link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/twotone.css">
Sharp:
<link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/sharp.css">
Each of these files contain the icons of the respective themes included as background-images (Base64 image-data). And here's how we can use this to test out the compatibility of a particular icon in our design before downloading it for use in the production environment.
STEP 1:
Include the stylesheet of the theme that you want to use. Eg: For the 'Outlined' theme, use the stylesheet for 'outline.css'
STEP 2:
Add the following classes to your own stylesheet:
.material-icons-new {
display: inline-block;
width: 24px;
height: 24px;
background-repeat: no-repeat;
background-size: contain;
}
.icon-white {
webkit-filter: contrast(4) invert(1);
-moz-filter: contrast(4) invert(1);
-o-filter: contrast(4) invert(1);
-ms-filter: contrast(4) invert(1);
filter: contrast(4) invert(1);
}
STEP 3:
Use the icon by adding the following classes to the <i>
tag:
material-icons-new
class
Icon name as shown on the material icons demo page, prefixed with the theme name followed by a hyphen.
Prefixes:
Outlined: outline-
Rounded: round-
Two-Tone: twotone-
Sharp: sharp-
Eg (for 'announcement' icon):
outline-announcement
, round-announcement
, twotone-announcement
, sharp-announcement
3) Use an optional 3rd class icon-white
for inverting the color from black to white (for dark backgrounds)
Changing icon size:
Since this is a background-image and not a font-icon, use the height
and width
properties of CSS to modify the size of the icons. The default is set to 24px in the material-icons-new
class.
Example:
Case I: For the Outlined Theme of the account_circle icon:
<link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/outline.css">
<i class="material-icons-new outline-account_circle"></i>
Optional (For dark backgrounds):
<i class="material-icons-new outline-account_circle icon-white"></i>
Case II: For the Sharp Theme of the assessment icon:
<link rel="stylesheet" href="https://storage.googleapis.com/non-spec-apps/mio-icons/latest/sharp.css">
<i class="material-icons-new sharp-assessment"></i>
(For dark backgrounds):
<i class="material-icons-new sharp-assessment icon-white"></i>
I can't stress enough that this is NOT THE RIGHT WAY to include the icons on your production environment. But if you have to scan through multiple icons on your in-development page, it does make the icon inclusion pretty easy and saves a lot of time.
Downloading the icon as SVG or PNG sure is a better option when it comes to site-speed optimization, but font-icons are a time-saver when it comes to the prototyping phase and checking if a particular icon goes with your design, etc.
I will update this post if and when Google comes up with a solution for this issue that does not involve downloading an icon for usage.
You do not need regular expressions to check if a substring exists in a string.
line = 'This,is,a,sample,string'
result = bool('sample' in line) # returns True
If you want to know if a string contains a pattern then you should use re.search
line = 'This,is,a,sample,string'
result = re.search(r'sample', line) # finds 'sample'
This is best used with pattern matching, for example:
line = 'my name is bob'
result = re.search(r'my name is (\S+)', line) # finds 'bob'
What happens in your code if $usertable
is not a valid table or doesn't include a column PartNumber or part is not a number.
You must escape $partid and also read the document for mysql_fetch_assoc() because it can return a boolean
"The
==
operator checks to see if twoObjects
are exactly the sameObject
."
http://leepoint.net/notes-java/data/strings/12stringcomparison.html
String
is an Object
in java, so it falls into that category of comparison rules.
I would prefer Session.Abandon()
Session.Clear()
will not cause End to fire and further requests from the client will not raise the Session Start event.
I think it would be interesting to write both of them in a way that only by switching some lines of code would give you one algorithm or the other, so that you will see that your dillema is not so strong as it seems to be at first.
I personally like the interpretation of BFS as flooding a landscape: the low altitude areas will be flooded first, and only then the high altitude areas would follow. If you imagine the landscape altitudes as isolines as we see in geography books, its easy to see that BFS fills all area under the same isoline at the same time, just as this would be with physics. Thus, interpreting altitudes as distance or scaled cost gives a pretty intuitive idea of the algorithm.
With this in mind, you can easily adapt the idea behind breadth first search to find the minimum spanning tree easily, shortest path, and also many other minimization algorithms.
I didnt see any intuitive interpretation of DFS yet (only the standard one about the maze, but it isnt as powerful as the BFS one and flooding), so for me it seems that BFS seems to correlate better with physical phenomena as described above, while DFS correlates better with choices dillema on rational systems (ie people or computers deciding which move to make on a chess game or going out of a maze).
So, for me the difference between lies on which natural phenomenon best matches their propagation model (transversing) in real life.
It took me a while, but I discovered that including the following was what made it possible to change the navbar color:
.navbar{
background-image: none;
}
<span class="label">My Label:</span>
<span class="text">My text</span>
Check this link out.
Open your terminal and type: Android_Sdk_Path/tools
Run ./monitor
Just for reference, a for
loop can be used after getting the first row to get the rest of the file:
with open('file.csv', newline='') as f:
reader = csv.reader(f)
row1 = next(reader) # gets the first line
for row in reader:
print(row) # prints rows 2 and onward
The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.
Your original string, a = 'a\\nb'
does not actually have two '\'
characters, the first one is an escape for the latter. If you do, print a
, you'll see that you actually have only one '\'
character.
>>> a = 'a\\nb'
>>> print a
a\nb
If, however, what you mean is to interpret the '\n'
as a newline character, without escaping the slash, then:
>>> b = a.replace('\\n', '\n')
>>> b
'a\nb'
>>> print b
a
b
If you are not comfortable with Docker depth configuration, iptables would be your friend.
iptables -t nat -A DOCKER -p tcp --dport ${YOURPORT} -j DNAT --to-destination ${CONTAINERIP}:${YOURPORT}
iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source ${CONTAINERIP} --destination ${CONTAINERIP} --dport ${YOURPORT}
iptables -A DOCKER -j ACCEPT -p tcp --destination ${CONTAINERIP} --dport ${YOURPORT}
This is just a trick, not a recommended way. This works with my scenario because I could not stop the container.
I just added the @Repository
annotation to Repository interface and @EnableJpaRepositories
("domain.repositroy-package") to the main class. It worked just fine.
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
Not sure where you add the json but if i do it like this with angular it works without the requestBody: angluar:
const params: HttpParams = new HttpParams().set('str1','val1').set('str2', ;val2;);
return this.http.post<any>( this.urlMatch, params , { observe: 'response' } );
java:
@PostMapping(URL_MATCH)
public ResponseEntity<Void> match(Long str1, Long str2) {
log.debug("found: {} and {}", str1, str2);
}
I am currently using Rob de la Cruz's reply:
Object.keys(obj)
And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.
if (!Object.keys) {
Object.keys = function(object) {
var keys = [];
for (var o in object) {
if (object.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.
Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.
My 5 (wrong) cents
'a' in "".join(['A']).lower()
Ouch, totally agree @jpp, I'll keep as an example of bad practice :(
The manual page (or the online GNU manual) pretty much explains everything.
For each result, command {}
is executed. All occurences of {}
are replaced by the filename. ;
is prefixed with a slash to prevent the shell from interpreting it.
Each result is appended to command
and executed afterwards. Taking the command length limitations into account, I guess that this command may be executed more times, with the manual page supporting me:
the total number of invocations of the command will be much less than the number of matched files.
Note this quote from the manual page:
The command line is built in much the same way that xargs builds its command lines
That's why no characters are allowed between {}
and +
except for whitespace. +
makes find detect that the arguments should be appended to the command just like xargs
.
Luckily, the GNU implementation of mv
can accept the target directory as an argument, with either -t
or the longer parameter --target
. It's usage will be:
mv -t target file1 file2 ...
Your find
command becomes:
find . -type f -iname '*.cpp' -exec mv -t ./test/ {} \+
From the manual page:
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.
There are 3 ways to that, i mention them in order of being the better way...
1-HTML way:
<input type="text" autocomplete="false" />
2-Javascript way:
document.getElementById("input-id").getAttribute("autocomplete") = "off";
3-jQuery way:
$('input').attr('autocomplete','off');
You can only delete with your time field, which is a number.
Delete from <measurement> where time=123456
will work. Remember not to give single quotes or double quotes. Its a number.
Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country
, X-AppEngine-Region
, X-AppEngine-City
and X-AppEngine-CityLatLong
headers.
An example looks like this:
X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733
Use single class name something like class="active" and add it only to current page instead of all pages. If you are at Home something like below:
<ul id="navigation">
<li class="active"><a href="/">Home</a></li>
<li class=""><a href="theatre.php">Theatre</a></li>
<li class=""><a href="programming.php">Programming</a></li>
</ul>
and your CSS like
li.active{
color: #640200;
}
I think your date comes from php and is written to html (dom) or? I have a php-function to prep all dates and timestamps. This return a formation that is be needed.
$timeForJS = timeop($datetimeFromDatabase['payedon'], 'js', 'local'); // save 10/12/2016 09:20 on var
this format can be used on js to create new Date...
<html>
<span id="test" data-date="<?php echo $timeForJS; ?>"></span>
<script>var myDate = new Date( $('#test').attr('data-date') );</script>
</html>
What i will say is, make your a own function to wrap, that make your life easyr. You can us my func as sample but is included in my cms you can not 1 to 1 copy and paste :)
function timeop($utcTime, $for, $tz_output = 'system')
{
// echo "<br>Current time ( UTC ): ".$wwm->timeop('now', 'db', 'system');
// echo "<br>Current time (USER): ".$wwm->timeop('now', 'db', 'local');
// echo "<br>Current time (USER): ".$wwm->timeop('now', 'D d M Y H:i:s', 'local');
// echo "<br>Current time with user lang (USER): ".$wwm->timeop('now', 'datetimes', 'local');
// echo '<br><br>Calculator test is users timezone difference != 0! Tested with "2014-06-27 07:46:09"<br>';
// echo "<br>Old time (USER -> UTC): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'system');
// echo "<br>Old time (UTC -> USER): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'local');
/** -- */
// echo '<br><br>a Time from db if same with user time?<br>';
// echo "<br>db-time (2019-06-27 07:46:09) time left = ".$wwm->timeleft('2019-06-27 07:46:09', 'max');
// echo "<br>db-time (2014-06-27 07:46:09) time left = ".$wwm->timeleft('2014-06-27 07:46:09', 'max', 'txt');
/** -- */
// echo '<br><br>Calculator test with other formats<br>';
// echo "<br>2014/06/27 07:46:09: ".$wwm->ntimeop('2014/06/27 07:46:09', 'db', 'system');
switch($tz_output){
case 'system':
$tz = 'UTC';
break;
case 'local':
$tz = $_SESSION['wwm']['sett']['tz'];
break;
default:
$tz = $tz_output;
break;
}
$date = new DateTime($utcTime, new DateTimeZone($tz));
if( $tz != 'UTC' ) // Only time converted into different time zone
{
// now check at first the difference in seconds
$offset = $this->tz_offset($tz);
if( $offset != 0 ){
$calc = ( $offset >= 0 ) ? 'add' : 'sub';
// $calc = ( ($_SESSION['wwm']['sett']['tzdiff'] >= 0 AND $tz_output == 'user') OR ($_SESSION['wwm']['sett']['tzdiff'] <= 0 AND $tz_output == 'local') ) ? 'sub' : 'add';
$offset = ['math' => $calc, 'diff' => abs($offset)];
$date->$offset['math']( new DateInterval('PT'.$offset['diff'].'S') ); // php >= 5.3 use add() or sub()
}
}
// create a individual output
switch( $for ){
case 'js':
$format = 'm/d/Y H:i'; // Timepicker use only this format m/d/Y H:i without seconds // Sett automatical seconds default to 00
break;
case 'js:s':
$format = 'm/d/Y H:i:s'; // Timepicker use only this format m/d/Y H:i:s with Seconds
break;
case 'db':
$format = 'Y-m-d H:i:s'; // Database use only this format Y-m-d H:i:s
break;
case 'date':
case 'datetime':
case 'datetimes':
$format = wwmSystem::$languages[$_SESSION['wwm']['sett']['isolang']][$for.'_format']; // language spezific output
break;
default:
$format = $for;
break;
}
$output = $date->format( $format );
/** Replacement
*
* D = day short name
* l = day long name
* F = month long name
* M = month short name
*/
$output = str_replace([
$date->format('D'),
$date->format('l'),
$date->format('F'),
$date->format('M')
],[
$this->trans('date', $date->format('D')),
$this->trans('date', $date->format('l')),
$this->trans('date', $date->format('F')),
$this->trans('date', $date->format('M'))
], $output);
return $output; // $output->getTimestamp();
}
int* test();
but it would be "more C++" to use vectors:
std::vector< int > test();
EDIT
I'll clarify some point. Since you mentioned C++, I'll go with new[]
and delete[]
operators, but it's the same with malloc/free.
In the first case, you'll write something like:
int* test() {
return new int[size_needed];
}
but it's not a nice idea because your function's client doesn't really know the size of the array you are returning, although the client can safely deallocate it with a call to delete[]
.
int* theArray = test();
for (size_t i; i < ???; ++i) { // I don't know what is the array size!
// ...
}
delete[] theArray; // ok.
A better signature would be this one:
int* test(size_t& arraySize) {
array_size = 10;
return new int[array_size];
}
And your client code would now be:
size_t theSize = 0;
int* theArray = test(theSize);
for (size_t i; i < theSize; ++i) { // now I can safely iterate the array
// ...
}
delete[] theArray; // still ok.
Since this is C++, std::vector<T>
is a widely-used solution:
std::vector<int> test() {
std::vector<int> vector(10);
return vector;
}
Now you don't have to call delete[]
, since it will be handled by the object, and you can safely iterate it with:
std::vector<int> v = test();
std::vector<int>::iterator it = v.begin();
for (; it != v.end(); ++it) {
// do your things
}
which is easier and safer.
Just Follow This
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
DISCLAIMER: The code below reportedly casued some crashes! Use with care.
according to THIS answer in Excel 2010 and above
CalculateUntilAsyncQueriesDone
halts macros until refresh is done
ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone
Add this, I think it is what you're looking for:
<meta name = "format-detection" content = "telephone=no">
Use CSS's :disabled
selector (for CSS3):
checkbox-style { }
checkbox-style:disabled { }
Or you need to use javascript to alter the style based on when you enable/disable it (Assuming it is being enabled/disabled based on your question).
The angular-split
component is not supported in Angular 6, so to make it compatible with Angular 6 install following dependency in your application
To get this working until it's updated use:
"dependencies": {
"angular-split": "1.0.0-rc.3",
"rxjs": "^6.2.2",
"rxjs-compat": "^6.2.2",
}
Both answers given worked for the problem I stated -- Thanks!
In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.
Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.
Remove the content of the folder \.m2\repository\org\apache\maven\plugins\maven-resource-plugin\2.7
. The cached info turned out to be the issue.
The only thing that worked for me was adding a .npmrc
file containing:
unsafe-perm = true
Adding the same config to package.json
didn't have any effect.
Using dplyr
(a bit like sapply..)
df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))
which gives:
glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7
from your df1 which was:
glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7
The other answers may have been useful years ago, but they are now out of date.
Given that a project has a tsconfig file, run this command...
tsc --watch
... to watch for changed files and compile as needed. The documentation explains:
Run the compiler in watch mode. Watch input files and trigger recompilation on changes. The implementation of watching files and directories can be configured using environment variable. See configuring watch for more details.
To answer the original question, recursive directory watching is possible even on platforms that don't have native support, as explained by the Configuring Watch docs:
The watching of directory on platforms that don’t support recursive directory watching natively in node, is supported through recursively creating directory watcher for the child directories using different options selected by TSC_WATCHDIRECTORY
Command + / or Ctrl + shift + 7 doesn't work for me (debian + colombian keyboard). In my case I changed the Atom keymap.cson file adding the following:
'.editor':
'ctrl-7': 'editor:toggle-line-comments'
and now it works!
If you set display:
to inline-block
, block
, flex
, ..., on the element with no content, then
For min-width
to take effect on a tag with no content, you only need to apply padding for either top or bot.
For min-height
to take effect on a tag with no content, you only need to apply padding for left or right.
There is another dimension to an earlier answer by @BlueMonkMN. The additional dimension is that the answer to the @Drahcir's title question as it is stated also depends on how we arrived at the string
value. To illustrate:
string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;
string s5 = "te" + "st";
object s6 = s5;
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));
Console.WriteLine("\n Case1 - A method changes the value:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));
Console.WriteLine("\n Case2 - Having only literals allows to arrive at a literal:");
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s5), s1 == s5, s1.Equals(s5));
Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s6), s1 == s6, s1.Equals(s6));
The output is:
True True True
Case1 - A method changes the value:
False True True
False False True
Case2 - Having only literals allows to arrive at a literal:
True True True
True True True
Ubuntu 16.04 comes with PHP7 as the standard, so there are no PHP5 packages
However if you like you can add a PPA to get those packages anyways:
Remove all the stock php packages
List installed php packages with dpkg -l | grep php| awk '{print $2}' |tr "\n" " "
then remove unneeded packages with sudo aptitude purge your_packages_here or if you want to directly remove them all use :
sudo aptitude purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`
Add the PPA
sudo add-apt-repository ppa:ondrej/php
Install your PHP Version
sudo apt-get update
sudo apt-get install php5.6
You can install php5.6 modules too ..
Verify your version
sudo php -v
Based on https://askubuntu.com/a/756186/532957 (thanks @AhmedJerbi)
Just add 'justify-content-around' class. that would automatically add gap between 2 divs.
Documentation: https://getbootstrap.com/docs/4.1/layout/grid/#horizontal-alignment
Sample:
<div class="row justify-content-around">
<div class="col-4">
One of two columns
</div>
<div class="col-4">
One of two columns
</div>
</div>
None of these solutions worked for me. The only workaround I could find was, adding all the min-width sizes together and applying that to the entire table. This obviously only works if you know all the column sizes in advanced, which I do. My tables look something like this:
var columns = [
{label: 'Column 1', width: 80 /* plus other column config */},
{label: 'Column 2', minWidth: 110 /* plus other column config */},
{label: 'Column 3' /* plus other column config */},
];
const minimumTableWidth = columns.reduce((sum, column) => {
return sum + (column.width || column.minWidth || 0);
}, 0);
tableElement.style.minWidth = minimumTableWidth + 'px';
This is an example and not recommended code. Fit the idea to your requirements. For example, the above is javascript and won't work if the user has JS disabled, etc.
1. You've got the right idea about how to design your resources, IMHO. I wouldn't change a thing.
2. Rather than trying to extend HTTP with more verbs, consider what your proposed verbs can be reduced to in terms of the basic HTTP methods and resources. For example, instead of an activate_login
verb, you could set up resources like: /api/users/1/login/active
which is a simple boolean. To activate a login, just PUT
a document there that says 'true' or 1 or whatever. To deactivate, PUT
a document there that is empty or says 0 or false.
Similarly, to change or set passwords, just do PUT
s to /api/users/1/password
.
Whenever you need to add something (like a credit) think in terms of POST
s. For example, you could do a POST
to a resource like /api/users/1/credits
with a body containing the number of credits to add. A PUT
on the same resource could be used to overwrite the value rather than add. A POST
with a negative number in the body would subtract, and so on.
3. I'd strongly advise against extending the basic HTTP status codes. If you can't find one that matches your situation exactly, pick the closest one and put the error details in the response body. Also, remember that HTTP headers are extensible; your application can define all the custom headers that you like. One application that I worked on, for example, could return a 404 Not Found
under multiple circumstances. Rather than making the client parse the response body for the reason, we just added a new header, X-Status-Extended
, which contained our proprietary status code extensions. So you might see a response like:
HTTP/1.1 404 Not Found
X-Status-Extended: 404.3 More Specific Error Here
That way a HTTP client like a web browser will still know what to do with the regular 404 code, and a more sophisticated HTTP client can choose to look at the X-Status-Extended
header for more specific information.
4. For authentication, I recommend using HTTP authentication if you can. But IMHO there's nothing wrong with using cookie-based authentication if that's easier for you.
You can right click the procedure, choose properties and see which permissions are granted to your login ID. You can then manually check off the "Execute" and alter permission for the proc.
Or to script this it would be:
GRANT EXECUTE ON OBJECT::dbo.[PROCNAME]
TO [ServerInstance\user];
GRANT ALTER ON OBJECT::dbo.[PROCNAME]
TO [ServerInstance\user];
CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.
Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.
Try something like this:
var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
method: 'JSONP',
url: url
}).
success(function(status) {
//your code when success
}).
error(function(status) {
//your code when fails
});
Rotating a vector 90 degrees is particularily simple.
(x, y)
rotated 90 degrees around (0, 0)
is (-y, x)
.
If you want to rotate clockwise, you simply do it the other way around, getting (y, -x)
.
Found Answer.......!!!!!!!
Officially Microsoft Office 2003 Interop is not supported on Windows server 2008 by Microsoft.
But after a lot of permutations & combinations with the code and search, we came across one solution which works for our scenario.
The solution is to plug the difference between the way Windows 2003 and 2008 maintains its folder structure, because Office Interop depends on the desktop folder for file open/save intermediately. The 2003 system houses the desktop folder under systemprofile which is absent in 2008.
So when we create this folder on 2008 under the respective hierarchy as indicated below; the office Interop is able to save the file as required. This Desktop folder is required to be created under
C:\Windows\System32\config\systemprofile
AND
C:\Windows\SysWOW64\config\systemprofile
This worked for me...
Also do check if .NET 1.1 is installed because its needed by Interop and ot preinstalled by Windows Server 2008
Or you can also Use SaveCopyas() method ist just take onargument as filename string)
Thanks Guys..!
I have this function in my toolbelt since years ago (all the function and variable names are messy and mixing Spanish and English, sorry for that).
It lets the user use ,
and .
to separate the decimals and will try to do the best if both symbols are used.
Public Shared Function TryCDec(ByVal texto As String, Optional ByVal DefaultValue As Decimal = 0) As Decimal
If String.IsNullOrEmpty(texto) Then
Return DefaultValue
End If
Dim CurAsTexto As String = texto.Trim.Replace("$", "").Replace(" ", "")
''// You can probably use a more modern way to find out the
''// System current locale, this function was done long time ago
Dim SepDecimal As String, SepMiles As String
If CDbl("3,24") = 324 Then
SepDecimal = "."
SepMiles = ","
Else
SepDecimal = ","
SepMiles = "."
End If
If InStr(CurAsTexto, SepDecimal) > 0 Then
If InStr(CurAsTexto, SepMiles) > 0 Then
''//both symbols was used find out what was correct
If InStr(CurAsTexto, SepDecimal) > InStr(CurAsTexto, SepMiles) Then
''// The usage was correct, but get rid of thousand separator
CurAsTexto = Replace(CurAsTexto, SepMiles, "")
Else
''// The usage was incorrect, but get rid of decimal separator and then replace it
CurAsTexto = Replace(CurAsTexto, SepDecimal, "")
CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
End If
End If
Else
CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
End If
''// At last we try to tryParse, just in case
Dim retval As Decimal = DefaultValue
Decimal.TryParse(CurAsTexto, retval)
Return retval
End Function
To copy a file from host to running container
docker exec -i $CONTAINER /bin/bash -c "cat > $CONTAINER_PATH" < $HOST_PATH
Based on Erik's answer and Mikl's and z0r's comments.
USE update_attribute instead of update_attributes
Updates a single attribute and saves the record without going through the normal validation procedure.
if a.update_attribute('state', a.state)
Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.
I know DOS and cmd prompt DOES NOT LIKE spaces in folder names. Your code starts with
cd c:\Program files\IIS Express
and it's trying to go to c:\Program in stead of C:\"Program Files"
Change the folder name and *.exe name. Hope this helps
I think you are searching for something like this one.
class test {
private $str = NULL;
public function newTest(){
$this->str .= 'function "newTest" called, ';
return $this;
}
public function bigTest(){
return $this->str . ' function "bigTest" called,';
}
public function smallTest(){
return $this->str . ' function "smallTest" called,';
}
public function scoreTest(){
return $this->str . ' function "scoreTest" called,';
}
}
$test = new test;
echo $test->newTest()->bigTest();
By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:
protected void renderImage(Canvas canvas)
{
Rect dest,drawRect ;
drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
(int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
(int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
(int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom
if(!mRotate) {
canvas.drawBitmap(mImage, drawRect, dest, null);
} else {
canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
canvas.drawBitmap(mImage, drawRect, dest, null);
canvas.restore();
}
}
Seems to me that you also wanted that image to be vertically centered within the container. (I didn't see any answer that provided that)
HTML
<div id="over">
<span class="Centerer"></span>
<img class="Centered" src="http://th07.deviantart.net/fs71/200H/f/2013/236/d/b/bw_avlonas_a5_beach_isles_wallpaper_image_by_lemnosexplorer-d6jh3i7.jpg" />
</div>
CSS
*
{
padding: 0;
margin: 0;
}
#over
{
position:absolute;
width:100%;
height:100%;
text-align: center; /*handles the horizontal centering*/
}
/*handles the vertical centering*/
.Centerer
{
display: inline-block;
height: 100%;
vertical-align: middle;
}
.Centered
{
display: inline-block;
vertical-align: middle;
}
Note: this solution is good to align any element within any element.
for IE7, when applying the .Centered
class on block elements, you will have to use another trick to get the inline-block
working. (that because IE6/IE7 dont play well with inline-block on block elements)
Try this
Sheets("your sheetname").range("A5:X50").Value = ""
You can also use
ActiveSheet.range
I don't think that you need to use each()
, you can use standard for loop
var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
var currentChild = children.eq(i);
// whatever logic you want
var oldPosition = currentChild.data("position");
}
this way you can have the standard for loop features like break
and continue
works by default
also, the debugging will be easier
Try, the following code..
@Override
public String toString() {
return this.name();
}
From the spring docs
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.
The <context-param>
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can then use the WebApplicationContext to get a handle on your beans.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info
Unlike what I see in every single other answer, you don't need to use pseudo elements in order to replace the content of a tag with an image
<div class="pvw-title">Facts</div>
div.pvw-title { /* No :after or :before required */
content: url("your URL here");
}
Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.
A: Yes, data
will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.
Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.
Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.
A: Correct. Note that the following tests are equivalent:
data != null
data != undefined
data !== null && data !== undefined
See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.
Try this:
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6'
This code may be helpful for you.
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
If you need only change url but prevent change state:
Change location with (add .replace if you want to replace in history):
this.$location.path([Your path]).replace();
Prevent redirect to your state:
$transitions.onBefore({}, function($transition$) {
if ($transition$.$to().name === '[state name]') {
return false;
}
});
Use the absolute value function ABS. The syntax is
ABS ( numeric_expression )
Following code calculates Palidrom for even length and odd length strings.
Not the best solution but works for both the cases
HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE
private static String getLongestPalindrome(String string) {
String odd = getLongestPalindromeOdd(string);
String even = getLongestPalindromeEven(string);
return (odd.length() > even.length() ? odd : even);
}
public static String getLongestPalindromeOdd(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex;
rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome
.length() ? currentPalindrome : longestPalindrome;
leftIndex--;
rightIndex++;
}
}
return longestPalindrome;
}
public static String getLongestPalindromeEven(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex - 1;
rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome
.length() ? currentPalindrome : longestPalindrome;
leftIndex--;
rightIndex++;
}
}
return longestPalindrome;
}
if exist <insert file name here> (
rem file exists
) else (
rem file doesn't exist
)
Or on a single line (if only a single action needs to occur):
if exist <insert file name here> <action>
for example, this opens notepad on autoexec.bat, if the file exists:
if exist c:\autoexec.bat notepad c:\autoexec.bat
Press Control+w, then hit q to close each window at a time.
Update: Also consider eckes answer which may be more useful to you, involving :on
(read below) if you don't want to do it one window at a time.
In API 23 or Higher (Android M, 6.0)
Turn On code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null;
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Turn OFF code
camManager.setTorchMode(cameraId, false);
And Permissions
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
ADDITIONAL EDIT
People still upvoting my answer so I decided to post additional code This was my solution for the problem back in the day:
public class FlashlightProvider {
private static final String TAG = FlashlightProvider.class.getSimpleName();
private Camera mCamera;
private Camera.Parameters parameters;
private CameraManager camManager;
private Context context;
public FlashlightProvider(Context context) {
this.context = context;
}
private void turnFlashlightOn() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String cameraId = null;
if (camManager != null) {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
Log.e(TAG, e.toString());
}
} else {
mCamera = Camera.open();
parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
private void turnFlashlightOff() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
String cameraId;
camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
if (camManager != null) {
cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
} else {
mCamera = Camera.open();
parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(parameters);
mCamera.stopPreview();
}
}
}
Pass in the straight XML instead of a dictionary.
You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:
$(function () {
$('.datetimepicker').datetimepicker(
{
format: 'Y-m-d h:m:s'
}
);
});`
The real answer to this question is, you can't do it.
Alternatives to CSS-only answers are not correct answers to this question, but if JS solutions are acceptable to you, then you should pick one of the JS or jQuery answers here.
However, as I said above, the true, correct answer is that you cannot do this in CSS reliably unless you're willing to accept the :not
operator with the [style*=display:none]
and other such negated selectors, which only works on inline styles, and is an overall poor solution.
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:
plt.plot(x,y,zorder=1)
plt.scatter(x,y,zorder=2)
plots the scatter symbols on top of the line, while
plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)
plots the line over the scatter symbols.
See, e.g., the zorder demo
var arr = [];_x000D_
var rows = 3;_x000D_
var columns = 2;_x000D_
_x000D_
for (var i = 0; i < rows; i++) {_x000D_
arr.push([]); // creates arrays in arr_x000D_
}_x000D_
console.log('elements of arr are arrays:');_x000D_
console.log(arr);_x000D_
_x000D_
for (var i = 0; i < rows; i++) {_x000D_
for (var j = 0; j < columns; j++) {_x000D_
arr[i][j] = null; // empty 2D array: it doesn't make much sense to do this_x000D_
}_x000D_
}_x000D_
console.log();_x000D_
console.log('empty 2D array:');_x000D_
console.log(arr);_x000D_
_x000D_
for (var i = 0; i < rows; i++) {_x000D_
for (var j = 0; j < columns; j++) {_x000D_
arr[i][j] = columns * i + j + 1;_x000D_
}_x000D_
}_x000D_
console.log();_x000D_
console.log('2D array filled with values:');_x000D_
console.log(arr);
_x000D_
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_
I had this issue on a Samsung device, Uninstalling the app gave the same message. The problem was that the app was also installed in the phone's "Secure Folder" area. Worth checking if this is your scenario.
I suggest creating a simple lookup table, which you can initialize in the static constructor to set any combination of characters to valid. This lets you do a quick, single check.
edit
Also, for speed, you'll want to initialize the capacity of your StringBuilder to the length of your input string. This will avoid reallocations. These two methods together will give you both speed and flexibility.
another edit
I think the compiler might optimize it out, but as a matter of style as well as efficiency, I recommend foreach instead of for.
There is always this of course:
(async () => {
await ...
// all of the script....
})();
// nothing else
This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611
I had a problem with this. I didn't use any clever $MyInvocation
stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit
then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax.
My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts.
When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...
Set is used for setting object references, as opposed to assigning a value.
I am using the AMD processor and had the same issue. To solve this go to control panel-> turn windows features on or off -> check the hyper-V checkbox and click Ok and restart your computer. Now you can create virtual device
I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.
String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";
SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);
Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);
This worked. Thanks.
I was using the Font Awesome library and was able to achieve this affect by tacking on the following to any html element.
<div class="fa fa-rotate-270">
My Test Text
</div>
Your mileage may vary.
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the []
operator. Usually there's no problem at all in using $str[0]
(and I'm pretty sure is much faster than the substr()
method).
There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr()
. Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.
You could also use regex to delete all the console.log() calls in your code if they're no longer required. Any decent IDE will allow you to search and replace these across an entire project, and allow you to preview the matches before committing the change.
\s*console\.log\([^)]+\);
This depends on the database server, but it is often called something like CEIL
or CEILING
. For example, in MySQL...
mysql> select ceil(10.5);
+------------+
| ceil(10.5) |
+------------+
| 11 |
+------------+
You can then do UPDATE PRODUCT SET price=CEIL(some_other_field);
A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.
Synopsys: A library to not only convert xml to json, but is also easy to debug (without circular errors) and recreate json back to xml. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"
I want to mention one important note regarding req.query
, because currently I am working on pagination functionality based on req.query
and I have one interesting example to demonstrate to you...
Example:
// Fetching patients from the database
exports.getPatients = (req, res, next) => {
const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;
const patientQuery = Patient.find();
let fetchedPatients;
// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
/**
* Construct two different queries
* - Fetch all patients
* - Adjusted one to only fetch a selected slice of patients for a given page
*/
patientQuery
/**
* This means I will not retrieve all patients I find, but I will skip the first "n" patients
* For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
*
* Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
* so I want to skip (7 * (2 - 1)) => 7 items
*/
.skip(pageSize * (currentPage - 1))
/**
* Narrow dont the amound documents I retreive for the current page
* Limits the amount of returned documents
*
* For example: If I got 7 items per page, then I want to limit the query to only
* return 7 items.
*/
.limit(pageSize);
}
patientQuery.then(documents => {
res.status(200).json({
message: 'Patients fetched successfully',
patients: documents
});
});
};
You will noticed +
sign in front of req.query.pageSize
and req.query.currentPage
Why? If you delete +
in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).
Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.
If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.
I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
table tr td:nth-child(2) {
background: #ccc;
}
Working example: http://jsfiddle.net/gqr3J/
This version of the accepted answer makes it a bit prettier if you are dealing with video lengths for example:
1:37:40 (1 hour / 37 minutes / 40 seconds)
1:00 (1 minute)
2:20 (2 minutes and 20 seconds)
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
var hourSeparator = ':';
var minuteSeparator = ':';
if(hours == 0){hours = '';hourSeparator = '';}
if (minutes < 10 && hours != 0) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+hourSeparator+minutes+minuteSeparator+seconds;
return time;
}
&a
gives address of a
- &p
gives address of p
.
int * * p_to_p = &p;
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
Use
GROUP BY year, month DESC";
Instead of
GROUP BY MONTH(t.summaryDateTime) DESC";
I tried to optimise SBF's and Michael's code a bit to make it more compact.
I am relying on PowerShell's type coercion where it automatically converts strings to enum values, so I didn't define the lookup dictionary.
I also pulled out the block that adds the new path to the list based on a condition, so that work is done once and stored in a variable for re-use.
It is then applied permanently or just to the Session depending on the $PathContainer
parameter.
We can put the block of code in a function or a ps1 file that we call directly from the command prompt. I went with DevEnvAddPath.ps1.
param(
[Parameter(Position=0,Mandatory=$true)][String]$PathChange,
[ValidateSet('Machine', 'User', 'Session')]
[Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session',
[Parameter(Position=2,Mandatory=$false)][Boolean]$PathPrepend=$false
)
[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';
if ($PathPersisted -notcontains $PathChange) {
$PathPersisted = $(switch ($PathPrepend) { $true{,$PathChange + $PathPersisted;} default{$PathPersisted + $PathChange;} }) | Where-Object { $_ };
$ConstructedEnvPath = $PathPersisted -join ";";
}
if ($PathContainer -ne 'Session')
{
# Save permanently to Machine, User
[Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}
# Update the current session
${env:Path} = $ConstructedEnvPath;
I do something similar for a DevEnvRemovePath.ps1.
param(
[Parameter(Position=0,Mandatory=$true)][String]$PathChange,
[ValidateSet('Machine', 'User', 'Session')]
[Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session'
)
[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';
if ($PathPersisted -contains $PathChange) {
$PathPersisted = $PathPersisted | Where-Object { $_ -ne $PathChange };
$ConstructedEnvPath = $PathPersisted -join ";";
}
if ($PathContainer -ne 'Session')
{
# Save permanently to Machine, User
[Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}
# Update the current session
${env:Path} = $ConstructedEnvPath;
So far, they seem to work.
You can solve this problem as here :) http://jsfiddle.net/MqM76/217/
HTML:
<input id="inpt" type="text" />
<div id="inpt-width"></div>
JS:
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
$('#inpt').on('input', function() {
var padding = 10; //Works as a minimum width
var valWidth = ($(this).textWidth() + padding) + 'px';
$('#'+this.id+'-width').html(valWidth);
$('#inpt').css('width', valWidth);
}).trigger('input');
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm()
method returns false
.
CodePointAt instead of charAt is safer to use. charAt may break when there are emojis in the strtng.
The -m
switch of PuTTY takes a path to a script file as an argument, not a command.
Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m
So you have to save your command (command_run
) to a plain text file (e.g. c:\path\command.txt
) and pass that to PuTTY:
putty.exe -ssh user@host -pw password -m c:\path\command.txt
Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).
A command-line syntax is identical, an output redirection added:
plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt
See Using the command-line connection tool Plink.
And with Plink, you can actually provide the command directly on its command-line:
plink.exe -ssh user@host -pw password command > output.txt
Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file
Try placing it on your body
body {
height: 100%;
background-image: url(../img/bg.svg);
background-size:100% 100%;
-o-background-size: 100% 100%;
-webkit-background-size: 100% 100%;
background-size:cover;
}
I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.
The below code is un-tested.
public class Team
{
[Key]
public int TeamId { get; set;}
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Match> HomeMatches { get; set; }
[InverseProperty("GuestTeam")]
public virtual ICollection<Match> GuestMatches { get; set; }
}
public class Match
{
[Key]
public int MatchId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships
Try this:
^[1-9]\d*$
...and some padding to exceed 30 character SO answer limit :-).
Came across this question and wanted something more simple... Try the following:
SELECT [processing-instruction(x)]=@Script FOR XML PATH(''),TYPE
Try this...
SELECT
AlarmEventTransactionTableTable.TxnID,
CASE
WHEN DeviceID IN('7', '10', '62', '58', '60',
'46', '48', '50', '137', '139',
'142', '143', '164') THEN '01'
WHEN DeviceID IN('8', '9', '63', '59', '61',
'47', '49', '51', '138', '140',
'141', '144', '165') THEN '02'
ELSE 'NA' END AS clocking,
AlarmEventTransactionTable.DateTimeOfTxn
FROM
multiMAXTxn.dbo.AlarmEventTransactionTable
Just remove highlighted string
SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)
- Abstract class
is one which can't be instantiated, i.e. its object
cannot be created.
- Abstract method
are method's declaration without its definition.
- A Non-abstract class
can only have Non-abstract methods.
- An Abstract class
can have both the Non-abstract as well as Abstract methods.
- If the Class
has an Abstract method
then the class must also be Abstract.
- An Abstract method
must be implemented by the very first Non-Abstract sub-class.
- Abstract class
in Design patterns
are used to encapsulate the behaviors that keeps changing.
You can fix it like this:
$scope.hoverIn = function(){
this.hoverEdit = true;
};
$scope.hoverOut = function(){
this.hoverEdit = false;
};
Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.
Also you need to put ngRepeat
on li
:
<ul>
<li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
{{task.name}}
<span ng-show="hoverEdit">
<a>Edit</a>
</span>
</li>
</ul>
However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:
ul li span {display: none;}
ul li:hover span {display: inline;}
i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.
every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.
this just returns a string passed from the console UPPERCASED.
app.js
var http = require('http');
var app = http.createServer(function(req, res) {
console.log('createServer');
});
app.listen(3000);
var io = require('socket.io').listen(app);
io.on('connection', function(socket) {
io.emit('Server 2 Client Message', 'Welcome!' );
socket.on('Client 2 Server Message', function(message) {
console.log(message);
io.emit('Server 2 Client Message', message.toUpperCase() ); //upcase it
});
});
index.html:
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
<script type='text/javascript'>
var socket = io.connect(':3000');
// optionally use io('http://localhost:3000');
// but make *SURE* it matches the jScript src
socket.on ('Server 2 Client Message',
function(messageFromServer) {
console.log ('server said: ' + messageFromServer);
});
</script>
</head>
<body>
<h5>Worlds smallest Socket.io example to uppercase strings</h5>
<p>
<a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
<br />
socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
</p>
</body>
</html>
to run:
npm init; // accept defaults
npm install socket.io http --save ;
node app.js &
use something like this port test to ensure your port is open.
now browse to http://localhost/index.html and use your browser console to send messages back to the server.
at best guess, when using http.createServer, it changes the following two lines for you:
<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();
i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.
April 10th 2020 Answer:
The suggested answer using Dimensions
is now discouraged. See: https://reactnative.dev/docs/dimensions
The recommended approach is using the useWindowDimensions
hook in React; https://reactnative.dev/docs/usewindowdimensions which uses a hook based API and will also update your value when the screen value changes (on screen rotation for example):
import {useWindowDimensions} from 'react-native';
const windowWidth = useWindowDimensions().width;
const windowHeight = useWindowDimensions().height;
Note: useWindowDimensions
is only available from React Native 0.61.0: https://reactnative.dev/blog/2019/09/18/version-0.61
The GNU site suggests this nice awk script, which prints both the words and their frequency.
Possible changes:
sort -nr
(and reverse word
and freq[word]
) to see the result in descending order.freq[3]++
- replace 3 with the column number.Here goes:
# wordfreq.awk --- print list of word frequencies
{
$0 = tolower($0) # remove case distinctions
# remove punctuation
gsub(/[^[:alnum:]_[:blank:]]/, "", $0)
for (i = 1; i <= NF; i++)
freq[$i]++
}
END {
for (word in freq)
printf "%s\t%d\n", word, freq[word]
}
Think of @class as telling the compiler "trust me, this exists".
Think of #import as copy-paste.
You want to minimize the number of imports you have for a number of reasons. Without any research, the first thing that comes to mind is it reduces compile time.
Notice that when you inherit from a class, you can't simply use a forward declaration. You need to import the file, so that the class you're declaring knows how it's defined.
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
public function getdata(){
$this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
$this->db->from('tblmaster t');
$this->db->join('country c', 't.country=c.country_id');
$this->db->join('state s', 't.state=s.state_id');
$this->db->join('city ct', 't.city=ct.city_id');
$this->db->order_by('t.id','desc');
$query = $this->db->get();
return $query->result();
}
Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):
import math
[x for x in xrange(2,10000) if all(x%t for t in xrange(2,int(math.sqrt(x))+1))]
Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)
Another way is probably just populating the prime numbers as we go:
primes = set()
def isPrime(x):
if x in primes:
return x
for i in primes:
if not x % i:
return None
else:
primes.add(x)
return x
filter(isPrime, range(2,10000))
From man 7 gitrevisions
:
HEAD names the commit on which you based the changes in the working tree. FETCH_HEAD records the branch which you fetched from a remote repository with your last git fetch invocation. ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation, so that you can easily change the tip of the branch back to the state before you ran them. MERGE_HEAD records the commit(s) which you are merging into your branch when you run git merge. CHERRY_PICK_HEAD records the commit which you are cherry-picking when you run git cherry-pick.
if you want just the parts of url after http://domain.com, try this:
<?php echo $_SERVER['REQUEST_URI']; ?>
if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.
if you want the full url, try this:
<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
Because timedelta is defined like:
class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])
All arguments are optional and default to 0.
You can easily say "Three days and four milliseconds" with optional arguments that way.
>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)
And for str casting, it returns a nice formatted value instead of __repr__
to improve readability. From docs:
str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)
>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'
Checkout documentation:
http://docs.python.org/library/datetime.html#timedelta-objects
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.
It should look like that :
#!/usr/bin/env python
or the real path
#!/usr/bin/python
You should also check the file have the right to be execute. chmod +x file.py
As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)
If you're trying to write unobtrusive JS code (and you should be), then you shouldn't use <body onload="">
.
It is my understanding that different browsers handle these two slightly differently but they operate similarly. In most browsers, if you define both, one will be ignored.
Here's another CSS only solution that works with any HTML layout.
It works with any element you need to switch. Whatever your toggle layout is you just put it inside a couple of elements with the if-collapsed
and if-not-collapsed
classes inside the toggle element.
The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed
class on the toggle.
It also requires the :not
selector, so it doesn't work on IE8.
HTML example:
<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
<!--You can put any valid html inside these!-->
<span class="if-collapsed">Open</span>
<span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
Less version:
[data-toggle="collapse"] {
&.collapsed .if-not-collapsed {
display: none;
}
&:not(.collapsed) .if-collapsed {
display: none;
}
}
CSS version:
[data-toggle="collapse"].collapsed .if-not-collapsed {
display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
display: none;
}
You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action
and Func
.
In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func
:
List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)
You could then call your GetJobs
method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.
P.S. You should use PascalCase for method names - GetJobs
, not getJobs
.
Use smem, which is an alternative to ps which calculates the USS and PSS per process. You probably want the PSS.
USS - Unique Set Size. This is the amount of unshared memory unique to that process (think of it as U for unique memory). It does not include shared memory. Thus this will under-report the amount of memory a process uses, but it is helpful when you want to ignore shared memory.
PSS - Proportional Set Size. This is what you want. It adds together the unique memory (USS), along with a proportion of its shared memory divided by the number of processes sharing that memory. Thus it will give you an accurate representation of how much actual physical memory is being used per process - with shared memory truly represented as shared. Think of the P being for physical memory.
How this compares to RSS as reported by ps and other utilities:
Notice: smem can also (optionally) output graphs such as pie charts and the like. IMO you don't need any of that. If you just want to use it from the command line like you might use ps -A v
, then you don't need to install the Python and Matplotlib recommended dependency.
Please see Why does the property I want to mock need to be virtual?
You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x)
call.
To Extend on @Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
I used this code to fix the issue of displaying items in the horizontal list.
new Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: array.length,
itemBuilder: (context, index){
return array[index];
},
),
],
),
);
I had the same problem and could not mount system as read/write. It would return
Usage: mount [-r] [-w] [-o options] [-t type] device directory
Or
operation not permitted. Access denied
Now this works on all rooted devices.
DO THE FOLLOWING IN TERMINAL EMULATOR
OR IN ADB SHELL
$ su
#mount - o rw,remount -t yaffs2 /system
Yaffs2
is the type of system partition. Replace it by the type of your system partition as obtained from executing the following
#cat /proc/mounts
Then check where /system
is appearing from the lengthy result
Extract of mine was like
mode=755,gid=1000 0 0
tmpfs /mnt/obb tmpfs rw,relatime,mode=755,gid=1000 0 0
none /dev/cpuctl cgroup rw,relatime,cpu 0 0/dev/block/platform/msm_sdcc.3/by-num/p10 /system ext4 ro,relatime,data=ordered 0 0
/dev/block/platform/msm_sdcc.3/by-num/p11 /cache ext4 rw,nosuid,nodev,relatime,data=ordered 0 0
So my system is ext4
. And my command was
$ su
#mount -o rw,remount -t ext4 /system
Done.
def extended_string (word, length) :
extra_long_word = word * (length//len(word) + 1)
required_string = extra_long_word[:length]
return required_string
print(extended_string("abc", 7))
Try to open eclipse.ini and replace
-Xmx1024m
with
-Xmx512m
My java version is 1.7 as you can see below
-Dosgi.requiredJavaVersion=1.7
so i didn't modify that parameter.
This worked for me ;-)
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.
NSArray *data = @[@"The String Value"];
if you need to send more than just 1 string value, you could also use
NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
then you can send it to the function like below
theFunction(data);
If you're getting source in Content Use the following method
try
{
var response = restClient.Execute<List<EmpModel>>(restRequest);
var jsonContent = response.Content;
var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);
foreach (EmpModel item in data)
{
listPassingData?.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine($"Data get mathod problem {ex} ");
}
You have use to repeat-y
as style="background-repeat:repeat-y;width: 200px;"
instead of style="repeat-y"
.
Try this inside the image tag or you can use the below css for the div
.div_backgrndimg
{
background-repeat: repeat-y;
background-image: url("/image/layout/lotus-dreapta.png");
width:200px;
}
If you are using Windows 10, install Windows Subsystem for Linux, WSL and Ubuntu.
$ ftp 192.168.1.39
Connected to 192.168.1.39.
............
230 Logged in successfully
Remote system type is MSDOS.
ftp> passive
Passive mode on.
ftp> passive
Passive mode off.
ftp>
If you look closely at the second output you can see that the new location for the libraries is used. Maybe there are still missing libraries that are part of the glibc.
I also think that all the libraries used by your program should be compiled against that version of glibc. If you have access to the source code of the program, a fresh compilation appears to be the best solution.
If you need an algorithm, try this: Convert the color from RGB space to HSV space (Hue, Saturation, Value). If your UI framework can't do it, check this article: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
Hue is in [0,360). To find the "opposite" color (think colorwheel), just add 180 degrees:
h = (h + 180) % 360;
For saturation and value, invert them:
l = 1.0 - l;
v = 1.0 - v;
Convert back to RGB. This should always give you a high contrast even though most combinations will look ugly.
If you want to avoid the "ugly" part, build a table with several "good" combinations, find the one with the least difference
def q(x):
return x*x
def diff(col1, col2):
return math.sqrt(q(col1.r-col2.r) + q(col1.g-col2.g) + q(col1.b-col2.b))
and use that.
I guess things have changed in python 3.4. This worked for me:
print("resp:" + json.dumps(resp.json()))
why you need a for-loop for this? the solution is very obvious:
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
that's it. no for-loop needed.
$host = $_SERVER['HTTP_HOST'];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
$domain = $matches[0];
$url = explode($domain, $host);
$subdomain = str_replace('.', '', $url[0]);
echo 'subdomain: '.$subdomain.'<br />';
echo 'domain: '.$domain.'<br />';
This is for Bootstrap 4.0, you only need to enter selected on the first line, it acts as a placeholder. The values are not necessary, but if you want to add value 0-... that is up to you. Much simpler than you may think:
<select class="custom-select">
<option selected>Open This</option>
<option value="">1st Choice</option>
<option value="">2nd Choice</option>
</select>
you can redirect stderr.
more explanation here, but having a command like:
MyCommand >log.txt 2>errors.txt
should grab the data you are looking for.
Also, as a trick, Windows bypasses that limitation if the path is prefixed with \\?\
(msdn)
Another trick if you have a root or destination that starts with a long path, perhaps SUBST
will help:
SUBST Q: "C:\Documents and Settings\MyLoginName\My Documents\MyStuffToBeCopied"
Xcopy Q:\ "d:\Where it needs to go" /s /e
SUBST Q: /D