Use for...in
loop:
for (var key in obj) {
console.log(' name=' + key + ' value=' + obj[key]);
// do some more stuff with obj[key]
}
I'm using this kind of routine for programmatically chaining animations.
final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
final Animation anim_in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
anim_out.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation)
{
////////////////////////////////////////
// HERE YOU CHANGE YOUR IMAGE CONTENT //
////////////////////////////////////////
//ui_image.setImage...
anim_in.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {}
});
ui_image.startAnimation(anim_in);
}
});
ui_image.startAnimation(anim_out);
var contentString = "Location: " + results[1].formatted_address;
google.maps.event.addListener(marker,'click', (function(){
infowindow.close();
infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, marker);
}));
thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.
Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.
Make sure you only have google-api-python-client
installed. If you have apiclient
installed, it will cause a collision. So, run the following:
sudo pip uninstall apiclient
Store it in a list. It is easier;
List<Foo> arr = new List<Foo>(dict.Values);
Of course if you specifically want it in an array;
Foo[] arr = (new List<Foo>(dict.Values)).ToArray();
You need to set the property server.contextPath
to /myWebApp
.
Check out this part of the documentation
The easiest way to set that property would be in the properties file you are using (most likely application.properties
) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation
EDIT
As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with server.servlet.contextPath
as has been correctly mentioned in this answer.
You just have to set UIFileSharingEnabled
(Application Supports iTunes file sharing
) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.
In the past, it was also necessary to define CFBundleDisplayName
(Bundle Display Name
), if it wasn't already there. More details here.
I had the same problem, when suddenly any test didn't appeared on Test Explorer window. I has the updated version of "NUnit3TestAdapter"
and after lots of searches and efforts, I found that I need set the following values in project properties: [In Solution Explorer window: right click on Project > Properties] Under Build tab, set Platform=x64, and set Platform target=x86 or Any CPU Build the project and all tests will be appear on Test Explorer window.
Important note: I came to a solution after seeing the next msg in the output window:
"Test run will use DLL(s) built for framework Framework45 and platform X86. Following DLL(s) will not be part of run: AutomationTests.dll is built for Framework Framework45 and Platform X64."
.NET 4.5 is an in place replacement for 4.0 - you will find the assemblies in the 4.0 directory.
See the blogs by Rick Strahl and Scott Hanselman on this topic.
You can also find the specific versions in:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework
or you may try something like
"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);
You use it like this to redirect on a particular URL and render component after redirecting from old-router to new-router.
<Route path="/old-router">
<Redirect exact to="/new-router"/>
<Route path="/new-router" component={NewRouterType}/>
</Route>
The name
is present inside the data
. You need to parse a JSON hierarchically to be able to fetch the data properly.
JSONObject jObject = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.
Note: This example uses the org.json.JSONObject
class and not org.json.simple.JSONObject
.
As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject
, I'm adding my comment details in the answer.
Try to use the
org.json.JSONObject
instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.
Sample from the link provided:
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
import org.apache.commons.io.filefilter.WildcardFileFilter;
.........
.........
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
The code above works great for me
This will give you the date in 24 hour format.
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
Since you are setting the layout explicitly you might want to try and put it in the default /layout folder not in the /layout-land since that is if you want Android to automatically handle rotation for you.
I just wrote this one-liner to select the first empty cell found in a column based on a selected cell. Only works on first column of selected cells. Modify as necessary
Selection.End(xlDown).Range("A2").Select
Use a concrete list type, e.g. ArrayList
instead of just List
.
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
I got to this thread while looking for the current directory of an executing process. In .net 1.1 Microsoft introduced:
Directory.GetCurrentDirectory();
Seems to work well (but doesn't return the name of the process itself).
Is there some simple equivalent to this keyword in C++?
No.
Depending on what you're trying to accomplish, there might be adequate (or even better) substitutes.
I've looked through some STL code (on linux, I think it's the one deriving from SGI's implementation). It has "concept assertions"; for instance, if you require a type which understands *x
and ++x
, the concept assertion would contain that code in a do-nothing function (or something similar). It does require some overhead, so it might be smart to put it in a macro whose definition depends on #ifdef debug
.
If the subclass relationship is really what you want to know about, you could assert in the constructor that T instanceof list
(except it's "spelled" differently in C++). That way, you can test your way out of the compiler not being able to check it for you.
This works like a charm in AutoCad VBA and I grabbed it from an excel forum. I don't know why you all make it so complicated?
FREQUENTLY ASKED QUESTIONS
Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this?
Answer: You can test to see if a directory exists using the VBA code below:
(Quotes below are omitted to avoid confusion of programming code)
If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then
MkDir "c:\TOTN\Excel\Examples"
End If
var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4; // error
// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above
An example of what I call Concatenated-declarations:
string Camnr = "",
Klantnr = "",
Ordernr = "",
Bonnr = "",
Volgnr = "",
Omschrijving = "",
Startdatum = "",
Bonprioriteit = "",
Matsoort = "",
Dikte = "",
Draaibaarheid = "",
Draaiomschrijving = "",
Orderleverdatum = "",
Regeltaakkode = "",
Gebruiksvoorkeur = "",
Regelcamprog = "",
Regeltijd = "",
Orderrelease = "";
Just my 2 cents, hope it helps someone somewhere.
You cannot undo the latest git add, but you can undo all add
s since the last commit. git reset
without a commit argument resets the index (unstages staged changes):
git reset
If you are using BitBucket your account can be put into read only mode for the following reasons:
- We are upgrading our storage segments and cannot accept new data.
- We are rolling out changes that require no new writes.
- The owner of the repository needs to upgrade their account to accept a higher number of users.
https://confluence.atlassian.com/display/BITBUCKET/Repositories+in+Read-Only+Mode
A useful feature for this is using static
As others have said, you have to create a class for your globals:
public static class Globals {
public const float PI = 3.14;
}
But you can import it like this in order to no longer write the class name in front of its static properties:
using static Globals;
[...]
Console.WriteLine("Pi is " + PI);
Look at the Inner Exception and find out what object might have caused the problem, you might have changed its name.
Go To AVD Manager, Click On The "Down Arrow" Next to The AVD Device that is showing this error, Click on "Show on Disk". Now Delete These Two Files "Cache.img" & "cache.img.qcow2" ..
Works Perfectly Fine For me.
In terms of it in regards to using the popular Twitter Bootstrap I feel like this type of bootstrapping is the action of integrating a modular component into a Web application without the Web application having to even acknowledge the modular component exists until it needs it or references it.
The developer can seamlessly integrate a default copy of the CSS Twitter Bootstrap theme by simply loading (referencing) it into the Web application. Vuola! Then you may need to override some of these changes, but you can do so in such a way that the resource/component is untouched and completely reusable.
This same concept is how Web Devs implement jQuery APIs and so on, but it's not really expressed by Devs as bootstrapping per se. What it does is it improves flexibility and reusability while allowing the isolation of different components/resources of an app to reside freely either on the same server/s or possibly on a CDN.
NOTE: In computing bootstrapping deals with the MBR and in UNIX it requires a special bootloader or manager which is a small program in ROM that loads the OS into RAM. If you think about it the same concept takes places in the action of the bootstrap loader checking the MBR and loading the OS based on this table which occurs without the OS having any idea that this takes place.
simple solution is this:
game.js:
document.addEventListener('click', printMousePos, true);
function printMousePos(e){
cursorX = e.pageX;
cursorY= e.pageY;
$( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}
Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id
and date
.
ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);
Then when inserting a record add the condition when a conflict is encountered:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value
This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.
The example above showing the import with ...sun.com/jsp/jstl/format is incorrect (meaning it didn't work for me).
Instead try the below -this import statement is valid
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %><%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>Format Date</title>
</head>
<body>
<c-rt:set var="now" value="<%=new java.util.Date()%>" />
<table border="1" cellpadding="0" cellspacing="0"
style="border-collapse: collapse" bordercolor="#111111"
width="63%" id="AutoNumber2">
<tr>
<td width="100%" colspan="2" bgcolor="#0000FF">
<p align="center">
<b>
<font color="#FFFFFF" size="4">Formatting:
<fmt:formatDate value="${now}" type="both"
timeStyle="long" dateStyle="long" />
</font>
</b>
</p>
</td>
</tr>
Use trigger
to fire your own event. When ever you change class add trigger with name
$("#main").on('click', function () {
$("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});
$('#chld').on('cssFontSet', function () {
alert("Red bg set ");
});
To truncate a string provided by the maximum limit without breaking a word use this:
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
public static function truncateStringWords($str, $maxlen): string
{
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
Here is one way of removing a duplicate object.
The blog class should be something like this or similar, like proper pojo
public class Blog {
private String title;
private String author;
private String url;
private String description;
private int hashCode;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object obj) {
Blog blog = (Blog)obj;
if(title.equals(blog.title) &&
author.equals(blog.author) &&
url.equals(blog.url) &&
description.equals(blog.description))
{
hashCode = blog.hashCode;
return true;
}else{
hashCode = super.hashCode();
return false;
}
}
}
And use it like this to remove duplicates objects. The key data structure here is the Set and LinkedHashSet. It will remove duplicates and also keep order of entry
Blog blog1 = new Blog();
blog1.setTitle("Game of Thrones");
blog1.setAuthor("HBO");
blog1.setDescription("The best TV show in the US");
blog1.setUrl("www.hbonow.com/gameofthrones");
Blog blog2 = new Blog();
blog2.setTitle("Game of Thrones");
blog2.setAuthor("HBO");
blog2.setDescription("The best TV show in the US");
blog2.setUrl("www.hbonow.com/gameofthrones");
Blog blog3 = new Blog();
blog3.setTitle("Ray Donovan");
blog3.setAuthor("Showtime");
blog3.setDescription("The second best TV show in the US");
blog3.setUrl("www.showtime.com/raydonovan");
ArrayList<Blog> listOfBlogs = new ArrayList<>();
listOfBlogs.add(blog1);
listOfBlogs.add(blog2);
listOfBlogs.add(blog3);
Set<Blog> setOfBlogs = new LinkedHashSet<>(listOfBlogs);
listOfBlogs.clear();
listOfBlogs.addAll(setOfBlogs);
for(int i=0;i<listOfBlogs.size();i++)
System.out.println(listOfBlogs.get(i).getTitle());
Running this should print
Game of Thrones
Ray Donovan
The second one will be removed because it is a duplicate of the first object.
This is what worked for me
Answered by Soren from another SO thread - CURL for WAMP
"There seems to be a bug somewhere. If you are experiencing this on Win 7 64 bit then try installing apache addon version 2.2.9 and php addon version 5.3.1 and switching to those in WAMP and then activating the CURL extension. That worked for me."
The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div
has role="dialog"
. When the screen reader notices that a div
becomes visible which has this role, it'll speak the label for that div
.
There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label>
HTML tag. With HTML modals the label is usually a <h>
header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader]
, and the screen reader will speak that header when the modal appears.
Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden
property is frequently redundant and can probably be skipped in most cases.
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
SELECT * FROM SysColumns WHERE Name like 'a%'
Will get you a list of columns, you will want to filter more to restrict it to your target table
From there you can construct some ad-hoc sql
$(document).ready(function(e) {
// executes when HTML-Document is loaded and DOM is ready
console.log("page is loading now");
});
$(document).load(function(e) {
//when html page complete loaded
console.log("completely loaded");
});
The easiest way to get the finger print is to switch from app to signed report by clicking the drop down and click build.
Then you will be able to see the sha1 fingerprint at the bottom pane where you see the debug report and stack trace. N.B remember to switch back to app when you want to run your app on a device or an emulator.
Improvement to @madprops answer - solution as a django management command:
import MySQLdb
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
host = settings.DATABASES['default']['HOST']
password = settings.DATABASES['default']['PASSWORD']
user = settings.DATABASES['default']['USER']
dbname = settings.DATABASES['default']['NAME']
db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(f'Changing table "{row[0]}"...')
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
Hope this helps anybody but me :)
The backslash \
is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /
.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
You need to get a reference of your form, and after that you can iterate the elements
collection. So, assuming for instance:
<form method="POST" action="submit.php" id="my-form">
..etc..
</form>
You will have something like:
var elements = document.getElementById("my-form").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.type === "text" && element.value === "")
console.log("it's an empty textfield")
}
Notice that in browser that would support querySelectorAll you can also do something like:
var elements = document.querySelectorAll("#my-form input[type=text][value='']")
And you will have in elements
just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:
var elements = document.querySelectorAll("#my-form input[type=text]")
for (var i = 0, element; element = elements[i++];) {
if (element.value === "")
console.log("it's an empty textfield")
}
You will basically save one check.
private void WaitNSeconds(int seconds)
{
if (seconds < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(seconds);
while (DateTime.Now < _desired) {
Thread.Sleep(1);
System.Windows.Forms.Application.DoEvents();
}
}
Insert input tags inside an unordered lists.Make the style-type none. Here's an example.
<ul>
Input1
<li> <input type="text" />
Input2
<li> <input type="text" />
<ul/>
Worked for me !
I too faced the same problem, and I did a "Factory data reset", and it worked fine after that.
It seems as of now, the only solution is still to install SublimeREPL.
To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:
To enable it, go to Preferences->Key Bindings - User, and copy this in there:
[
{"keys":["ctrl+r"] ,
"caption": "SublimeREPL: Python - RUN current file",
"command": "run_existing_window_command",
"args":
{
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
},
]
Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.
You can use the Enum.TryParse method:
Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
// You now have the value in age
}
The easy way to do is, put all your files including index.html or something with all resources such as CSS, JS etc. in a folder public or you can name it whatever you want and now you can use express js and just tell app to use the _dirname as :
In your server.js using express add these
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
and if you want to have seprate directory add new dir under public directory and use that path "/public/YourDirName"
SO what we are doing here exactly? we are creating express instance named app and we are giving the adress if the public directory to access all the resources. Hope this helps !
I made a short answer, that sums up most of the above, to clean the uncertainty that was in my head as a beginner:
Opposed to Objective-C, no variable can contain nil in Swift, so the Optional variable type was added (variables suffixed by "?"):
var aString = nil //error
The big difference is that the Optional variables don't directly store values (as a normal Obj-C variables would) they contain two states: "has a value" or "has nil":
var aString: String? = "Hello, World!"
aString = nil //correct, now it contains the state "has nil"
That being, you can check those variables in different situations:
if let myString = aString? {
println(myString)
}
else {
println("It's nil") // this will print in our case
}
By using the "!" suffix, you can also access the values wrapped in them, only if those exist. (i.e it is not nil):
let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!
println(anotherString) //it will print "Hello, World!"
That's why you need to use "?" and "!" and not use all of them by default. (this was my biggest bewilderment)
I also agree with the answer above: Optional type cannot be used as a boolean.
Try this:
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();
Simply add the eventhandler to the button when creating it.
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
if(isset($_POST['submit']))
{
if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
{
$uname = $_POST['login_username'];
$pass = $_POST['login_password'];
$res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and password='$pass' ";
$query=mysql_query($res)or die (mysql_error());
list($result,$uname,$role) = mysql_fetch_row($query);
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
{
if($result>0)
{
header ('Location:Dashboard.php');
}
else
{
header ('Location:loginform.php');
}
}
It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...
It's quite simple. First give your app the permission RECEIVE_BOOT_COMPLETED. Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.
Your Manifest.xml should now look like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jjoe64"> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application> <receiver android:name=".BootCompletedIntentReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <service android:name=".BackgroundService"/> </application> </manifest>
As the last step you have to implement the Receiver. This receiver just starts your background service.
package com.jjoe64; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.jjoe64.BackgroundService; public class BootCompletedIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent pushIntent = new Intent(context, BackgroundService.class); context.startService(pushIntent); } } }
From http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html
Here's a simple solution with lambdas:
root = Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen",
not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.mainloop()
This will make the screen exit fullscreen when escape is pressed, and toggle fullscreen when F11 is pressed.
Without enumerate()
:
>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]
If you added a library to the project structure (rather than via maven, that would be different), be sure it is included as a dependency for the relevant module.
Project Structure -> Modules -> Dependencies
if (combo1.SelectedIndex > -1)
{
// do something
}
if any item is selected selected index will be greater than -1
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
Here is a nice and simple way to do it (but on CENTOS), without braking the operating system.
yum install scl-utils
next
yum install centos-release-scl-rh
And lastly you install the version that you want, lets say python3.5
yum install rh-python35
And lastly:
scl enable rh-python35 bash
Since MAC-OS is a unix operating system, the way to do it it should be quite similar.
None of the APIs will give you a count because there really isn't any Amazon specific API to do that. You have to just run a list-contents and count the number of results that are returned.
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
As others have noted, embedding function pointers directly inside your structure is usually reserved for special purposes, like a callback function.
What you probably want is something more like a virtual method table.
typedef struct client_ops_t client_ops_t;
typedef struct client_t client_t, *pno;
struct client_t {
/* ... */
client_ops_t *ops;
};
struct client_ops_t {
pno (*AddClient)(client_t *);
pno (*RemoveClient)(client_t *);
};
pno AddClient (client_t *client) { return client->ops->AddClient(client); }
pno RemoveClient (client_t *client) { return client->ops->RemoveClient(client); }
Now, adding more operations does not change the size of the client_t
structure. Now, this kind of flexibility is only useful if you need to define many kinds of clients, or want to allow users of your client_t
interface to be able to augment how the operations behave.
This kind of structure does appear in real code. The OpenSSL BIO layer looks similar to this, and also UNIX device driver interfaces have a layer like this.
Here is a general purpose function for converting either a timedelta
object or a regular number (in the form of seconds or minutes, etc.) to a nicely formatted string. I took mpounsett's fantastic answer on a duplicate question, made it a bit more flexible, improved readibility, and added documentation.
You will find that it is the most flexible answer here so far since it allows you to:
Function:
from string import Formatter
from datetime import timedelta
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'seconds']:
remainder = int(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = int(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = int(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = int(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = int(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('W', 'D', 'H', 'M', 'S')
constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
values[field], remainder = divmod(remainder, constants[field])
return f.format(fmt, **values)
Demo:
>>> td = timedelta(days=2, hours=3, minutes=5, seconds=8, microseconds=340)
>>> print strfdelta(td)
02d 03h 05m 08s
>>> print strfdelta(td, '{D}d {H}:{M:02}:{S:02}')
2d 3:05:08
>>> print strfdelta(td, '{D:2}d {H:2}:{M:02}:{S:02}')
2d 3:05:08
>>> print strfdelta(td, '{H}h {S}s')
51h 308s
>>> print strfdelta(12304, inputtype='s')
00d 03h 25m 04s
>>> print strfdelta(620, '{H}:{M:02}', 'm')
10:20
>>> print strfdelta(49, '{D}d {H}h', 'h')
2d 1h
This becomes simpler by using git-filter-repo.
In order to move project2/sub/dir
to project1/sub/dir
:
# Create a new repo containing only the subdirectory:
git clone project2 project2_subdir
cd project2_subdir
git filter-repo --force --path sub/dir
# Merge the new repo:
cd ../project1
git remote add project2_subdir ../project2_subdir/
git merge remotes/project2_subdir/master --allow-unrelated-histories
git remote remove project2_subdir
To install the tool simply: pip3 install git-filter-repo
(more details and options in README)
# Before: (root)
.
|-- project1
| `-- 3
`-- project2
|-- 1
`-- sub
`-- dir
`-- 2
# After: (project1)
.
+-- 3
+-- sub
+-- dir
+-- 2
You can use Reflection to obtain the actual names of the properties.
http://www.csharp-examples.net/reflection-property-names/
If you need a way to assign a "String Name" to a property, why don't you write an attribute that you can reflect over to get the string name?
[StringName("MyStringName")]
private string MyProperty
{
get { ... }
}
Use ORACLE equivalent of getdate()
which is sysdate
. Read about here.
Getdate() belongs to SQL Server , will not work on Oracle.
Other option is current_date
max
is built in function which takes first argument an iterable
(like list or tuple)
keyword argument key
has it's default value None
but it accept function to evaluate, consider it as wrapper which evaluates iterable based on function
Consider this example dictionary:
d = {'aim':99, 'aid': 45, 'axe': 59, 'big': 9, 'short': 995, 'sin':12, 'sword':1, 'friend':1000, 'artwork':23}
Ex:
>>> max(d.keys())
'sword'
As you can see if you only pass the iterable without kwarg(a function to key
) it is returning maximum value of key(alphabetically)
Ex. Instead of finding max value of key alphabetically you might need to find max key by length of key:
>>>max(d.keys(), key=lambda x: len(x))
'artwork'
in this example lambda function is returning length of key which will be iterated hence while evaluating values instead of considering alphabetically it will keep track of max length of key and returns key which has max length
Ex.
>>> max(d.keys(), key=lambda x: d[x])
'friend'
in this example lambda function is returning value of corresponding dictionary key which has maximum value
If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s///
should be all you need:
#!/usr/bin/perl -w
use strict;
main();
sub main{
my $foo = "blahblahblah";
print '$foo: ' , replace("lah","ar",$foo) , "\n"; #$foo: barbarbar
}
sub replace {
my ($from,$to,$string) = @_;
$string =~s/$from/$to/ig; #case-insensitive/global (all occurrences)
return $string;
}
you have to call set and add functions on chart object before calling redraw.
chart.xAxis[0].setCategories([2,4,5,6,7], false);
chart.addSeries({
name: "acx",
data: [4,5,6,7,8]
}, false);
chart.redraw();
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
I think that you have a mismatched config for 'fetch' and 'push' so this has caused default fetch/push to not round trip properly. Fortunately you have fetched the branches that you subsequently deleted so you should be able to recreate them with an explicit push.
git push origin origin/contact_page:contact_page origin/new_pictures:new_pictures
There are many ways of running separate threads in .Net, each has different behaviors. Do you need to continue running the thread after the GUI quits? Do you need to pass information between the thread and GUI? Does the thread need to update the GUI? Should the thread do one task then quit, or should it continue running? The answers to these questions will tell you which method to use.
There is a good async method article at the Code Project web site that describes the various methods and provides sample code.
Note this article was written before the async/await pattern and Task Parallel Library were introduced into .NET.
The contract of the hash code makes clear that:
"If two objects are equal according to the Object method, then calling the hashCode method on each of the two objects must produce the same integer result."
So your assumption:
"To clarify, the equals method is overridden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo."
is wrong and you are breaking the contract. If we look at the "contains" method of Set interface, we have that:
boolean contains(Object o);
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element "e" such that o==null ? e==null : o.equals(e)
To accomplish what you want, you can use a Map where you define the key and store your element with the key that defines how objects are different or equal to each other.
Try to add following line in root folder index.php after php starts:
ob_start();
This works for me.
The following works for me.
#include <algorithm>
void toUpperCase(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}
int main()
{
std::string str = "hello";
toUpperCase(&str);
}
Let's learn from an example. Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val()
will return "Jose", i.e. the current value.
Hope it helps.
There is a public domain TimeZone library for .NET. Really useful. It will answer your needs.
Solving the general-case timezone problem is harder than you think.
I think what's missing here is that when you do:
>pip install .
to install a local package with a setup.py, it installs a package that is visible to all the conda envs that use the same version of python. Note I am using the conda version of pip!
e.g., if I'm using python2.7 it puts the local package here:
/usr/local/anaconda/lib/python2.7/site-packages
If I then later create a new conda env with python=2.7 (= the default):
>conda create --name new
>source activate new
And then do:
(new)>conda list // empty - conda is not aware of any packages yet
However, if I do:
(new)>pip list // the local package installed above is present
So in this case, conda does not know about the pip package, but the package is available to python.
However, If I instead install the local package (again using pip) after I've created (and activated) the new conda env, now conda sees it:
(new)>conda list // sees that the package is there and was installed by pip
So I think the interaction between conda and pip has some issues - ie, using pip to install a local package from within one conda env makes that package available (but not seen via conda list) to all other conda envs of the same python version.
have you looked at layoutIfNeeded?
The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?
layoutIfNeeded Lays out the subviews if needed.
- (void)layoutIfNeeded
Discussion Use this method to force the layout of subviews before drawing.
Availability Available in iPhone OS 2.0 and later.
This happens because Oracle dropped support for Windows XP (which doesn't have RegDeleteKeyExA
used by the installer in its ADVAPI32.DLL
by the way) as described in http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-July/009005.html. Yet while the official support for XP has ended, the Java binaries are still (as of Java 8u20 EA b05 at least) XP-compatible - only the installer isn't...
Because of that, the solution is actually quite easy:
get 7-Zip (or any other good unpacker), unpack the distribution .exe manually, it has one .zip file inside of it (tools.zip
), extract it too,
use unpack200
from JDK8 to unpack all .pack files to .jar files (older unpacks won't work properly); JAVA_HOME
environment variable should be set to your Java unpack root, e.g. "C:\Program Files\Java\jdk8" - you can specify it implicitly by e.g.
SET JAVA_HOME=C:\Program Files\Java\jdk8
Unpack all files with a single command (in batch file):
FOR /R %%f IN (*.pack) DO "%JAVA_HOME%\bin\unpack200.exe" -r -v "%%f" "%%~pf%%~nf.jar"
Unpack all files with a single command (command line from JRE root):
FOR /R %f IN (*.pack) DO "bin\unpack200.exe" -r -v "%f" "%~pf%~nf.jar"
Unpack by manually locating the files and unpacking them one-by-one:
%JAVA_HOME%\bin\unpack200 -r packname.pack packname.jar
where packname
is for example rt
point the tool you want to use (e.g. Netbeans) to the %JAVA_HOME%
and you're good to go.
Note: you probably shouldn't do this just to use Java 8 in your web browser or for any similar reason (installing JRE 8 comes to mind); security flaws in early updates of major Java version releases are (mind me) legendary, and adding to that no real support for neither XP nor Java 8 on XP only makes matters much worse. Not to mention you usually don't need Java in your browser (see e.g. http://nakedsecurity.sophos.com/2013/01/15/disable-java-browsers-homeland-security/ - the topic is already covered on many pages, just Google it if you require further info). In any case, AFAIK the only thing required to apply this procedure to JRE is to change some of the paths specified above from \bin\
to \lib\
(the file placement in installer directory tree is a bit different) - yet I strongly advise against doing it.
See also: How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?, JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object
This will effectively remove all class names which begins with prefix
from a node's class
attribute. Other answers do not support SVG elements (as of writing this), but this solution does:
$.fn.removeClassPrefix = function(prefix){
var c, regex = new RegExp("(^|\\s)" + prefix + "\\S+", 'g');
return this.each(function(){
c = this.getAttribute('class');
this.setAttribute('class', c.replace(regex, ''));
});
};
you can integrate to LDAP or AD as well. It works well.
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
They both seems to navigate to the given webpage and quoting @matt answer:
navigate().to()
andget()
do exactly the same thing.
Single-Page Applications are an exception to this.
The difference between these two methods comes not from their behavior, but from the behavior in the way the application works and how browser deal with it.
navigate().to()
navigates to the page by changing the URL like doing forward/backward navigation.
Whereas, get()
refreshes the page to changing the URL.
So, in cases where application domain changes, both the method behaves similarly. That is, page is refreshed in both the cases. But, in single-page applications, while navigate().to()
do not refreshes the page, get()
do.
Moreover, this is the reason browser history is getting lost when get()
is used due to application being refreshed.
Originally answered: https://stackoverflow.com/a/33868976/3619412
From the man page:
search, -S text|/text/ Perform a substring search of formula names for text. If text is surrounded with slashes, then it is interpreted as a regular expression. If no search term is given, all available formula are displayed.
For your purposes, brew search
will suffice.
http://geosoft.no/development/javastyle.html#Specific
is
prefix should be used for boolean variables and methods.
isSet
,isVisible
,isFinished
,isFound
,isOpen
This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.
Setter methods for boolean variables must have set prefix as in:
void setFound(boolean isFound);
There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:
boolean hasLicense(); boolean canEvaluate(); boolean shouldAbort = false;
You could write a stored procedure that iterates over the transaction that you have proposed. The iterator would be the cursor for the table that contains the source data.
NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above
You can send it as raw xml
<test>or like this</test>
If you declare the paramater2 as XElement data type
This should also work:
document.documentElement.className = 'myClass';
Edit:
IE 10 reckons it's readonly; yet:
Opera works:
I can also confirm it works in:
If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine
library, there is a built in ListField
that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.
The key is the sql query, which you will set up as a string:
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
Note that there are a lot of ways to specify NOT. Another one that works just as well is:
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";
Here is a full example of how to use it:
$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);
while ($row = mysql_fetch_assoc($result) {
//do stuff
}
You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array
which means that $row['field1']
will give you the value for field1
on the current row, and $row['field2']
will give you the value for field2
.
Note that if the column(s) could have NULL
values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL
values:
$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";
Objective-C:
[button.titleLabel setFont: [button.titleLabel.font fontWithSize: sizeYouWant]];
Swift:
button.titleLabel?.font = button.titleLabel?.font.fontWithSize(sizeYouWant)
will do nothing more than changing the font size.
Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html
Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.
There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices
.
I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.
You may like to try something like this which covers all the bases, including not relying on whitespace after the number:
>>> import re
>>> numeric_const_pattern = r"""
... [-+]? # optional sign
... (?:
... (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
... |
... (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
... )
... # followed by optional exponent part if desired
... (?: [Ee] [+-]? \d+ ) ?
... """
>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)
>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']
>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")
['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")
['-2.03e+99']
>>>
For easy copy-pasting:
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
This is because you're using getActivity()
inside an inner class. Try using:
SherlockFragmentActivity.this.getActivity()
instead, though there's really no need for the getActivity()
part. In your case,
SherlockFragmentActivity .this
should suffice.
try this
String url = "jdbc:mysql://localhost:3306/<dbname>";
String user = "<username>";
String password = "<password>";
conn = DriverManager.getConnection(url, user, password);
You cannot guarantee that the automatically-generated WSDL will match the WSDL from which you create the service interface.
In your scenario, you should place the WSDL file on your web site somewhere, and have consumers use that URL. You should disable the Documentation
protocol in the web.config so that "?wsdl" does not return a WSDL. See <protocols>
Element.
Also, note the first paragraph of that article:
This topic is specific to a legacy technology. XML Web services and XML Web service clients should now be created using Windows Communication Foundation (WCF).
The original form is nearly perfect, you just have to omit prereq after CASE:
SELECT
CASE
WHEN prereq IS NULL THEN ' '
ELSE prereq
END AS prereq
FROM test;
This has been answered above, but I wanted to suggest an alternative.
When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names
from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles
, select this to change back to the original view.
This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.
Can even work with Associative Arrays.. for example in a class.
class Test {
const
CAN = [
"can bark", "can meow", "can fly"
],
ANIMALS = [
self::CAN[0] => "dog",
self::CAN[1] => "cat",
self::CAN[2] => "bird"
];
static function noParameter() {
return self::ANIMALS[self::CAN[0]];
}
static function withParameter($which, $animal) {
return "who {$which}? a {$animal}.";
}
}
echo Test::noParameter() . "s " . Test::CAN[0] . ".<br>";
echo Test::withParameter(
array_keys(Test::ANIMALS)[2], Test::ANIMALS["can fly"]
);
// dogs can bark.
// who can fly? a bird.
I think is more robust to use regular expressions:
import re
for i, line in enumerate(content):
print line if not (re.match('\r?\n', line)) else pass
This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n'
as expression
Depends on how the switch in particular language works, however in most languages when no case is matched, the execution falls through the switch statement without warning. Imagine you expected some set of values and handled them in switch, however you get another value in the input. Nothing happens and you don't know nothing happened. If you caught the case in default, you would know there was something wrong.
Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.
To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r
in front of the string with your actual path.
For example,
from pathlib import Path
dataFolder = Path(r'D:\Desktop dump\example.txt')
Source: The easy way to deal with file paths on Windows, Mac and Linux
I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css
).
Make sure your servlet doesn't contain the "/" urlPattern.
I hope this worked for u too,
- Axel Montini
What about like this?
public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
return true;
}
You still have to pass a value to the parameter from C# but it is an optional ref param.
It's very simple, first convert the number to string using the toString() method in JavaScript and then use split() method to convert the string to an array of individual characters.
For example, the number is num, then
const numberDigits = num.toString().split('');
This script lists most of what you are looking for and can hopefully be modified to you needs. Note that it is creating a permanent table in there - you might want to change it. It is a subset from a larger script that also summarises backup and job information on various servers.
IF OBJECT_ID('tempdb..#DriveInfo') IS NOT NULL
DROP TABLE #DriveInfo
CREATE TABLE #DriveInfo
(
Drive CHAR(1)
,MBFree INT
)
INSERT INTO #DriveInfo
EXEC master..xp_fixeddrives
IF OBJECT_ID('[dbo].[Tmp_tblDatabaseInfo]', 'U') IS NOT NULL
DROP TABLE [dbo].[Tmp_tblDatabaseInfo]
CREATE TABLE [dbo].[Tmp_tblDatabaseInfo](
[ServerName] [nvarchar](128) NULL
,[DBName] [nvarchar](128) NULL
,[database_id] [int] NULL
,[create_date] datetime NULL
,[CompatibilityLevel] [int] NULL
,[collation_name] [nvarchar](128) NULL
,[state_desc] [nvarchar](60) NULL
,[recovery_model_desc] [nvarchar](60) NULL
,[DataFileLocations] [nvarchar](4000)
,[DataFilesMB] money null
,DataVolumeFreeSpaceMB INT NULL
,[LogFileLocations] [nvarchar](4000)
,[LogFilesMB] money null
,LogVolumeFreeSpaceMB INT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Tmp_tblDatabaseInfo]
SELECT
@@SERVERNAME AS [ServerName]
,d.name AS DBName
,d.database_id
,d.create_date
,d.compatibility_level
,CAST(d.collation_name AS [nvarchar](128)) AS collation_name
,d.[state_desc]
,d.recovery_model_desc
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 0 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS DataFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 0 and m.database_id = d.database_id) AS DataFilesMB
,NULL
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 1 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS LogFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 1 and m.database_id = d.database_id) AS LogFilesMB
,NULL
FROM sys.databases d
WHERE d.database_id > 4 --Exclude basic system databases
UPDATE [dbo].[Tmp_tblDatabaseInfo]
SET DataFileLocations =
CASE WHEN LEN(DataFileLocations) > 4 THEN LEFT(DataFileLocations,LEN(DataFileLocations)-2) ELSE NULL END
,LogFileLocations =
CASE WHEN LEN(LogFileLocations) > 4 THEN LEFT(LogFileLocations,LEN(LogFileLocations)-2) ELSE NULL END
,DataFilesMB =
CASE WHEN DataFilesMB > 0 THEN DataFilesMB * 8 / 1024.0 ELSE NULL END
,LogFilesMB =
CASE WHEN LogFilesMB > 0 THEN LogFilesMB * 8 / 1024.0 ELSE NULL END
,DataVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( DataFileLocations,1))
,LogVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( LogFileLocations,1))
select * from [dbo].[Tmp_tblDatabaseInfo]
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
I suggest that you add
#!/usr/bin/env python
instead of #!/usr/bin/python
at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env
you make sure that the system finds python and delegates the script's execution to it.
As said before to make the script executable, something like:
chmod u+x name_of_script.py
should do.
Gears and HTML5 have a progress event in the HttpRequest
object for submitting a file upload via AJAX.
http://developer.mozilla.org/en/Using_files_from_web_applications
Your other options as already answered by others are:
Technically there is a forth option, similar to YouTube upload, with Gears or HTML5 you can use blobs to split a file into small chunks and individually upload each chunk. On completion of each chunk you can update the progress status.
Not free, but ReSharper is definitely one recommendation.
I tried this on my VM machine
change the permissions /home/vagrant (did a chmod 700 on it)
now i can ssh directly into my boxes
Well any Javascript object functions sort-of like a "map"
randomObject['hello'] = 'world';
Typically people build simple objects for the purpose:
var myMap = {};
// ...
myMap[newKey] = newValue;
edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.
13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.
Set the activity content from a layout resource.
ie.,setContentView(R.layout.basicXml)
;
There is no fixed limit on how large a JSON data block is or any of the fields.
There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.
Super easy way is as following. No need to create a function.
<select onchange="window.location = this.options[this.selectedIndex].value">
<option value="">Switch Language</option>
<option value="{{ url('/en') }}">English</option>
<option value="{{ url('/ps') }}">????</option>
<option value="{{ url('/fa') }}">???</option>
</select>
it works for me with a jar target:
<jar jarfile="${server.jar}" basedir="${classes.dir}" excludes="**/client/">
<manifest>
<attribute name="Main-Class" value="${mainServer.class}" />
</manifest>
</jar>
this code include all files in "classes.dir" but exclude the directory "client" from the jar.
By this code for formating price in product list
echo Mage::helper('core')->currency($_product->getPrice());
Look at the API documentation for the java.util.Calendar class and its derivatives (you may be specifically interested in the GregorianCalendar class).
You have stumbled over the general problem with encodings: How can I tell in which encoding a file is?
Answer: You can't unless the file format provides for this. XML, for example, begins with:
<?xml encoding="utf-8"?>
This header was carefully chosen so that it can be read no matter the encoding. In your case, there is no such hint, hence neither your editor nor Python has any idea what is going on. Therefore, you must use the codecs
module and use codecs.open(path,mode,encoding)
which provides the missing bit in Python.
As for your editor, you must check if it offers some way to set the encoding of a file.
The point of UTF-8 is to be able to encode 21-bit characters (Unicode) as an 8-bit data stream (because that's the only thing all computers in the world can handle). But since most OSs predate the Unicode era, they don't have suitable tools to attach the encoding information to files on the hard disk.
The next issue is the representation in Python. This is explained perfectly in the comment by heikogerlach. You must understand that your console can only display ASCII. In order to display Unicode or anything >= charcode 128, it must use some means of escaping. In your editor, you must not type the escaped display string but what the string means (in this case, you must enter the umlaut and save the file).
That said, you can use the Python function eval() to turn an escaped string into a string:
>>> x = eval("'Capit\\xc3\\xa1n\\n'")
>>> x
'Capit\xc3\xa1n\n'
>>> x[5]
'\xc3'
>>> len(x[5])
1
As you can see, the string "\xc3" has been turned into a single character. This is now an 8-bit string, UTF-8 encoded. To get Unicode:
>>> x.decode('utf-8')
u'Capit\xe1n\n'
Gregg Lind asked: I think there are some pieces missing here: the file f2 contains: hex:
0000000: 4361 7069 745c 7863 335c 7861 316e Capit\xc3\xa1n
codecs.open('f2','rb', 'utf-8')
, for example, reads them all in a separate chars (expected) Is there any way to write to a file in ASCII that would work?
Answer: That depends on what you mean. ASCII can't represent characters > 127. So you need some way to say "the next few characters mean something special" which is what the sequence "\x" does. It says: The next two characters are the code of a single character. "\u" does the same using four characters to encode Unicode up to 0xFFFF (65535).
So you can't directly write Unicode to ASCII (because ASCII simply doesn't contain the same characters). You can write it as string escapes (as in f2); in this case, the file can be represented as ASCII. Or you can write it as UTF-8, in which case, you need an 8-bit safe stream.
Your solution using decode('string-escape')
does work, but you must be aware how much memory you use: Three times the amount of using codecs.open()
.
Remember that a file is just a sequence of bytes with 8 bits. Neither the bits nor the bytes have a meaning. It's you who says "65 means 'A'". Since \xc3\xa1
should become "Ã " but the computer has no means to know, you must tell it by specifying the encoding which was used when writing the file.
NOTE: answer is dependent upon jQuery 1.6.1+
$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true); // To select via value
Thanks for the comment, .get
won't work since it returns a DOM element, not a jQuery one. Keep in mind the .eq
function can be used outside of the selector as well if you prefer.
$('#selectBox option').eq(3).prop('selected', true);
You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:
$("#selectBox").val("3");
Note: .val(3)
works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option>
requires you to use .val("hello")
)
A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.
Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
private Mutex mutex;
private bool mutexCreated;
public App()
{
string mutexId = $"Global\\{GetType().GUID}";
mutex = new Mutex(true, mutexId, out mutexCreated);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!mutexCreated)
{
MessageBox.Show("Already started!");
Shutdown();
}
}
Because Mutex implements IDisposable it is released automatically but for completeness call dispose:
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
mutex.Dispose();
}
Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).
public class SingleApplication : Application
{
private Mutex mutex;
private bool mutexCreated;
public SingleApplication()
{
string mutexId = $"Global\\{GetType().GUID}";
MutexAccessRule allowEveryoneRule = new MutexAccessRule(
new SecurityIdentifier(WellKnownSidType.WorldSid, null),
MutexRights.FullControl,
AccessControlType.Allow);
MutexSecurity securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// initiallyOwned: true == false + mutex.WaitOne()
mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);
}
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
if (mutexCreated)
{
try
{
mutex.ReleaseMutex();
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
mutex.Dispose();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!mutexCreated)
{
MessageBox.Show("Already started!");
Shutdown();
}
}
}
How about writing your own concat method?
public static Stream<T> concat(Stream<? extends T> a,
Stream<? extends T> b,
Stream<? extends T> args)
{
Stream<T> concatenated = Stream.concat(a, b);
for (Stream<T> stream : args)
{
concatenated = Stream.concat(concatenated, stream);
}
return concatenated;
}
This at least makes your first example a lot more readable.
var textWidth = (function (el) {
el.style.position = 'absolute';
el.style.top = '-1000px';
document.body.appendChild(el);
return function (text) {
el.innerHTML = text;
return el.clientWidth;
};
})(document.createElement('div'));
$('#subscribeForm').validate( {
rules: {
list: {
required: true,
minlength: 1
}
}
});
I think this will make sure at least one is checked.
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.
perhaps a:
i=2
while i < n:
if something:
do something
i += 1
else:
do something else
i = 2 #restart the loop
Array is a sequential list of items
int item = value;
int [] one_dimensional_array = { value, value, value, .., value };
int [][] two_dimensional_array =
{
{ value, value, value, .. value },
{ value, value, value, .. value },
.. .. .. ..
{ value, value, value, .. value }
};
If it's an object, then it's the same concept
Object item = new Object();
Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };
Object [][] two_dimensional_array =
{
{ new Object(), new Object(), .. new Object() },
{ new Object(), new Object(), .. new Object() },
.. .. ..
{ new Object(), new Object(), .. new Object() }
};
In case of objects, you need to either assign it to null
to initialize them using new Type(..)
, classes like String
and Integer
are special cases that will be handled as following
String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };
In general you can create arrays that's M
dimensional
int [][]..[] array =
// ^ M times [] brackets
{{..{
// ^ M times { bracket
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ M times } bracket
;
It's worthy to note that creating an M
dimensional array is expensive in terms of Space. Since when you create an M
dimensional array with N
on all the dimensions, The total size of the array is bigger than N^M
, since each array has a reference, and at the M-dimension there is an (M-1)-dimensional array of references. The total size is as following
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
// ^ ^ array reference
// ^ actual data
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
This can be done with standard POSIX shell grammar.
Here is a simple count_entries
function:
#!/usr/bin/env sh
count_entries()
{
# Emulating Bash nullglob
# If argument 1 is not an existing entry
if [ ! -e "$1" ]
# argument is a returned pattern
# then shift it out
then shift
fi
echo $#
}
for a compact definition:
count_entries(){ [ ! -e "$1" ]&&shift;echo $#;}
Featured POSIX compatible file counter by type:
#!/usr/bin/env sh
count_files()
# Count the file arguments matching the file operator
# Synopsys:
# count_files operator FILE [...]
# Arguments:
# $1: The file operator
# Allowed values:
# -a FILE True if file exists.
# -b FILE True if file is block special.
# -c FILE True if file is character special.
# -d FILE True if file is a directory.
# -e FILE True if file exists.
# -f FILE True if file exists and is a regular file.
# -g FILE True if file is set-group-id.
# -h FILE True if file is a symbolic link.
# -L FILE True if file is a symbolic link.
# -k FILE True if file has its `sticky' bit set.
# -p FILE True if file is a named pipe.
# -r FILE True if file is readable by you.
# -s FILE True if file exists and is not empty.
# -S FILE True if file is a socket.
# -t FD True if FD is opened on a terminal.
# -u FILE True if the file is set-user-id.
# -w FILE True if the file is writable by you.
# -x FILE True if the file is executable by you.
# -O FILE True if the file is effectively owned by you.
# -G FILE True if the file is effectively owned by your group.
# -N FILE True if the file has been modified since it was last read.
# $@: The files arguments
# Output:
# The number of matching files
# Return:
# 1: Unknown file operator
{
operator=$1
shift
case $operator in
-[abcdefghLkprsStuwxOGN])
for arg; do
# If file is not of required type
if ! test "$operator" "$arg"; then
# Shift it out
shift
fi
done
echo $#
;;
*)
printf 'Invalid file operator: %s\n' "$operator" >&2
return 1
;;
esac
}
count_files "$@"
Example usages:
count_files -f log*.txt
count_files -d datadir*
It is General sibling combinator
and is explained in @Salaman's answer very well.
What I did miss is Adjacent sibling combinator
which is +
and is closely related to ~
.
example would be
.a + .b {
background-color: #ff0000;
}
<ul>
<li class="a">1st</li>
<li class="b">2nd</li>
<li>3rd</li>
<li class="b">4th</li>
<li class="a">5th</li>
</ul>
.b
.a
.a
in HTMLIn example above it will mark 2nd li
but not 4th.
.a + .b {_x000D_
background-color: #ff0000;_x000D_
}
_x000D_
<ul>_x000D_
<li class="a">1st</li>_x000D_
<li class="b">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="a">5th</li>_x000D_
</ul>
_x000D_
Since coffee script has no var
statement it automatically inserts it for all variables in the coffee-script, that way it prevents the compiled JavaScript version from leaking everything into the global namespace.
So since there's no way to make something "leak" into the global namespace from the coffee-script side of things on purpose, you need to define your global variables as properties of the global object.
attach them as properties on window
This means you need to do something like window.foo = 'baz';
, which handles the browser case, since there the global object is the window
.
In Node.js there's no window
object, instead there's the exports
object that gets passed into the wrapper that wraps the Node.js module (See: https://github.com/ry/node/blob/master/src/node.js#L321 ), so in Node.js what you would need to do is exports.foo = 'baz';
.
Now let us take a look at what it states in your quote from the docs:
...targeting both CommonJS and the browser: root = exports ? this
This is obviously coffee-script, so let's take a look into what this actually compiles to:
var root;
root = (typeof exports !== "undefined" && exports !== null) ? exports : this;
First it will check whether exports
is defined, since trying to reference a non existent variable in JavaScript would otherwise yield an SyntaxError (except when it's used with typeof
)
So if exports
exists, which is the case in Node.js (or in a badly written WebSite...) root will point to exports
, otherwise to this
. So what's this
?
(function() {...}).call(this);
Using .call
on a function will bind the this
inside the function to the first parameter passed, in case of the browser this
would now be the window
object, in case of Node.js it would be the global context which is also available as the global
object.
But since you have the require
function in Node.js, there's no need to assign something to the global
object in Node.js, instead you assign to the exports
object which then gets returned by the require
function.
After all that explanation, here's what you need to do:
root = exports ? this
root.foo = -> 'Hello World'
This will declare our function foo
in the global namespace (whatever that happens to be).
That's all :)
A rather nice way to handle this for missing COM classes:
Dim o:Set o = Nothing
On Error Resume Next
Set o = CreateObject("foo.bar")
On Error Goto 0
If o Is Nothing Then
Response.Write "Oups, foo.bar isn't installed on this server!"
Else
Response.Write "Foo bar found, yay."
End If
When you do this:
export type Fruit = "Orange" | "Apple" | "Banana"
...you are creating a type called Fruit
that can only contain the literals "Orange"
, "Apple"
and "Banana"
. This type extends String
, hence it can be assigned to String
. However, String
does NOT extend "Orange" | "Apple" | "Banana"
, so it cannot be assigned to it. String
is less specific. It can be any string.
When you do this:
export type Fruit = "Orange" | "Apple" | "Banana"
const myString = "Banana";
const myFruit: Fruit = myString;
...it works. Why? Because the actual type of myString
in this example is "Banana"
. Yes, "Banana"
is the type. It is extends String
so it's assignable to String
. Additionally, a type extends a Union Type when it extends any of its components. In this case, "Banana"
, the type, extends "Orange" | "Apple" | "Banana"
because it extends one of its components. Hence, "Banana"
is assignable to "Orange" | "Apple" | "Banana"
or Fruit
.
Assuming your row number is in B1
, you can use INDIRECT
:
=INDIRECT("A" & B1)
This takes a cell reference as a string (in this case, the concatenation of A
and the value of B1
- 5), and returns the value at that cell.
Simple method:
public boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
public String normalizeOnlyLettersNumbers(String str) {
if (!isBlank(str)) {
return str.replaceAll("[^\\p{L}\\p{Nd}]+", "");
} else {
return "";
}
}
db.query('select * from login',(err, results, fields)=>{
if(err){
console.log('error in fetching data')
}
var string=JSON.stringify(results);
console.log(string);
var json = JSON.parse(string);
// to get one value here is the option
console.log(json[0].name);
})
It's because of other projects in your solutions. e.g If you have two projects in your solution as Project A and Project B. If Project A is not successful build and then Project B data migration will fail. So you should unload Project A and add the migration to Project B again.
I think this is not a good answer but hope this help.
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
Another way is to use the -t
switch to ssh
:
ssh -t user@server "sudo script"
See man ssh
:
-t Force pseudo-tty allocation. This can be used to execute arbi-
trary screen-based programs on a remote machine, which can be
very useful, e.g., when implementing menu services. Multiple -t
options force tty allocation, even if ssh has no local tty.
No actual difference unless you get the type string. There when you use reflection or GetType() you get {Name = "Boolean" FullName = "System.Boolean"} for both.
How about netstat?
http://support.microsoft.com/kb/907980
The command is netstat -anob
.
(Make sure you run command as admin)
I get:
C:\Windows\system32>netstat -anob
Active Connections
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 692
RpcSs
[svchost.exe]
TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 7540
[Skype.exe]
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:623 0.0.0.0:0 LISTENING 564
[LMS.exe]
TCP 0.0.0.0:912 0.0.0.0:0 LISTENING 4480
[vmware-authd.exe]
And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
For Sql Azure the following query works :
ALTER TABLE [TableName] ADD DEFAULT 'DefaultValue' FOR ColumnName
GO
On top of all the other answers, one thing not mentionned yet is decoupling :
Let me speak about a real world production code,that I have been dealing with :
A very big software, made of >300 projects (with visual studio), mostly build as static lib and finally all link together in one huge executable , you end up with the following problems :
-Link time is extremely long. You might end up by more than 15min of link, for let's say 10s of compilation time -Some tools are on their knee with such a big executable , like memory check tools that must instrument the code. You might fall into reaching limits that had been seen as fools.
More problematic is the decoupling of your software : on this real world example, headers files of every project were reacheable from any others projects. As a consequence it was extremely easy for one developer to add dependencies; it was just about including the header, because link at the end will allwaws find symbols. It ends up by horrible cycling dependencies and complete mess.
With shared library, it's a bit of extra work because developer must edit the project build system to add the dependent library. I observed that shared library code tends to offer a cleaner code API.
A SimpleDateFormat
, as its name indicates, formats Date
s. Not a Calendar
. So, if you want to format a GregorianCalendar
using a SimpleDateFormat
, you must convert the Calendar
to a Date
first:
dateFormat.format(calendar.getTime());
And what you see printed is the toString()
representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple
)DateFormat
.
Finally, to convert from a String
to a Date
, you should also use a (Simple
)DateFormat
(its parse()
method), rather than splitting the String
as you're doing. This will give you a Date
object, and you can create a Calendar
from the Date
by instanciating it (Calendar.getInstance()
) and setting its time (calendar.setTime()
).
My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.
This script will run after the entire page has loaded.
<script type="text/javascript">
$(window).load(function() {
//This execute when entire finished loaded
window.print();
});
</script>
My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..
A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:
public class Variables {
List<Object> listVariable; // declared but not assigned
final int aFinalVariableExample = 5; // declared, assigned and said to be final!
Integer foo(List<Object> someOtherObjectListVariable) {
// declare..
Object iAmAlsoAVariable;
// assign a value..
iAmAlsoAVariable = 5;
// change its value..
iAmAlsoAVariable = 8;
someOtherObjectListVariable.add(iAmAlsoAVariable);
return new Integer();
}
}
So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:
A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.
A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.
I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.
This is your dataArray
:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson
can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
also you can reimplement protected member QWidget::closeEvent()
void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
// do what you need here
// then call parent's procedure
QWidget::closeEvent(event);
}
You might want to look into open2 and open3 in case you need bidirectional communication.
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
Starting from the answer given by @chaos, but with a few modifications:
You should always use ORDER BY
if you use LIMIT
. There is no implicit order guaranteed for an RDBMS table. You may usually get rows in the order of the primary key, but you can't rely on this, nor is it portable.
If you order by in the descending order, you don't need to know the number of rows in the table beforehand.
You must give a correlation name (aka table alias) to a derived table.
Here's my version of the query:
SELECT `id`
FROM (
SELECT `id`, `val`
FROM `big_table`
ORDER BY `id` DESC
LIMIT $n
) AS t
WHERE t.`val` = $certain_number;
There is a specific property for this. It is called CharacterCasing and you could set it to Upper
TextBox1.CharacterCasing = CharacterCasing.Upper;
In ASP.NET you could try to add this to your textbox style
style="text-transform:uppercase;"
You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp
I got this issue after updating the dlls/nuget.
I could solve this manually by correcting the .csproj file. Mostly the version wasn't updated in the file. For example :
<Analyzer> Include="..\packages\Microsoft.CodeAnalysis.**VersionCheckAnalyzer.2.9.1**\analyzers\dotnet\Microsoft.CodeAnalysis.VersionCheckAnalyzer.dll"/>
<Analyzer> Include="..\packages\Microsoft.CodeAnalysis.**VersionCheckAnalyzer.2.9.7**\analyzers\dotnet\Microsoft.CodeAnalysis.VersionCheckAnalyzer.dll"/>
Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.
If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.
This sounds like your browser is caching your css. If you are using Firefox, try loading your page using Shift-Reload.
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
target.fadeOut(300, function(){ $(this).remove();});
or
$('#target_id').fadeOut(300, function(){ $(this).remove();});
Duplicate: How to "fadeOut" & "remove" a div in jQuery?
Try in this way
Adapter class :
public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
private final List<ContentItem> items;
private final OnItemClickListener listener;
public ContentAdapter(List<ContentItem> items, OnItemClickListener listener) {
this.items = items;
this.listener = listener;
}
@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item, parent, false);
return new ViewHolder(v);
}
@Override public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), listener);
}
@Override public int getItemCount() {
return items.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private ImageView image;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.image);
}
public void bind(final ContentItem item, final OnItemClickListener listener) {
name.setText(item.name);
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}
In your Activity or fragment :
ContentAdapter adapter = new ContentAdapter(itemList, this);
Note : Implement the OnItemClickListener based on context given by you in activity or fragment and overide methods.
Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com
line. In Perl, say, something like
my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;
say decode_base64($sanitized_str);
might be what you want. It produces
This is simple ASCII Base64 for StackOverflow exmaple.
You probably can't. Here's something that comes close. You won't get content to flow around it if there's space below.
http://jsfiddle.net/ThnLk/1289
.stuck {
position: fixed;
top: 10px;
left: 10px;
bottom: 10px;
width: 180px;
overflow-y: scroll;
}
You can do a percentage height as well:
http://jsfiddle.net/ThnLk/1287/
.stuck {
max-height: 100%;
}
If you need it in SELECT section can use like this.
SELECT ct.ID,
ISNULL(NULLIF(ct.LaunchDate, ''), null) [LaunchDate]
FROM [dbo].[CustomerTable] ct
you can replace the null
with your substitution value.
Drop you database, then it will work.
You can perform the following steps to drop your database
step 1 : Go to mongodb installation directory, default dir is "C:\Program Files\MongoDB\Server\4.2\bin"
step 2 : Start mongod.exe directly or using command prompt and minimize it.
step 3 : Start mongo.exe directly or using command prompt and run the following command
i) use yourDatabaseName (use show databases if you don't remember database name)
ii) db.dropDatabase()
This will remove your database. Now you can insert your data, it won't show error, it will automatically add database and collection.
Starting with .net framework 4.6 / .net core 1.0, there is now a AppContext.BaseDirectory, which should give the same result as AppDomain.CurrentDomain.BaseDirectory
, except that AppDomains were not part of the .net core 1.x /.net standard 1.x API.
AppContext.BaseDirectory
just mvn clean install -DskipTests
Yes, this is definitely possible. You'll need to have the php function in a separate php file. Here's an example using $.post:
$.post(
'yourphpscript.php', // location of your php script
{ name: "bob", user_id: 1234 }, // any data you want to send to the script
function( data ){ // a function to deal with the returned information
$( 'body ').append( data );
});
And then, in your php script, just echo the html you want. This is a simple example, but a good place to get started:
<?php
echo '<div id="test">Hello, World!</div>';
?>
Check the code below and the link to MDN
// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")
// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))
// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
_x000D_
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
At the place of uniqueIntNo
put unique integer number like this:
mNotificationManager.notify(uniqueIntNo, builder.build());
By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)
JSONArray list = new JSONArray();
if (jsonArray != null){
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
boolean flag;
try {
flag = jsonArray.get(i).toString().equals(obj.toString());
//Excluding the item at position
if (!flag)
{
list.put(jsonArray.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonArray = list;
Please note that Github now allows an unlimited number of collaborators even on a free account. See https://github.com/pricing.
Try this from the command line to change the git config details.
git config --global --replace-all user.name "Your New Name"
git config --global --replace-all user.email "Your new email"
Stop the mysqld server.
System Preferences
> MySQL
> Stop MySQL Server
sudo systemctl stop mysqld.service
Start the server in safe mode with privilege bypass
sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
In a new terminal window:
sudo /usr/local/mysql/bin/mysql -u root
This will open the mysql command line. From here enter:
UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';
FLUSH PRIVILEGES;
quit
Stop the mysqld server again and restart it in normal mode.
sudo /usr/local/mysql/support-files/mysql.server restart
sudo systemctl restart mysqld
I had the same problem when I used Vesta, which uses nginx with apache. The problem was that after applying all updates Apache started listening to 443 for https. The solution was just to comment out the 443 stuff in ports.conf. This is because nginx also uses this port.
This is perhaps a bit late, but may help someone. I come across similar issue with Iterable
in my codebase and solution was to use for each
without explicitly calling values.iterator();
.
int size = 0;
for(T value : values) {
size++;
}
C# - serialData is ReceivedEventHandler
in TextBox
.
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));
Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.
Serial:
Serial.print(rnd);
Serial.( '\n' ); //carriage return
In python:
>>> import re
>>> p='^(?!index\.php\?[0-9]+).*$'
>>> s1='index.php?12345'
>>> re.match(p,s1)
>>> s2='index.html?12345'
>>> re.match(p,s2)
<_sre.SRE_Match object at 0xb7d65fa8>
I have solved this if you are using array called for 2 tables. Example you have,
$tableA['yellow']
and $tableA['blue']
. You are getting these 2 values and you want to add another element inside them to separate them by their type
.
foreach ($tableA['yellow'] as $value) {
$value->type = 'YELLOW'; //you are adding new element named 'type'
}
foreach ($tableA['blue'] as $value) {
$value->type = 'BLUE'; //you are adding new element named 'type'
}
So, both of the tables value will have new element called type
.
For me brew postinstall python3
didn't work. I found this solution on the GitHub Homebrew issues page:
$ brew rm python
$ rm -rf /usr/local/opt/python
$ brew cleanup
$ brew install python3
HTML5 basically behaves as if the trailing slash is not there. There is no such thing as a self-closing tag in HTML5 syntax.
Self-closing tags on non-void elements like <p/>
, <div/>
will not work at all. The trailing slash will be ignored, and these will be treated as opening tags. This is likely to lead to nesting problems.
This is true regardless of whether there is whitespace in front of the slash: <p />
and <div />
also won't work for the same reason.
Self-closing tags on void elements like <br/>
or <img src="" alt=""/>
will work, but only because the trailing slash is ignored, and in this case that happens to result in the correct behaviour.
The result is, anything that worked in your old "XHTML 1.0 served as text/html" will continue to work as it did before: trailing slashes on non-void tags were not accepted there either whereas the trailing slash on void elements worked.
One more note: it is possible to represent an HTML5 document as XML, and this is sometimes dubbed "XHTML 5.0". In this case the rules of XML apply and self-closing tags will always be handled. It would always need to be served with an XML mime type.
The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.
When you say modify the page and return the modified page
what do you mean?
To make sure the height of a view is 50% of the screen then we can create two sub LinearLayouts in a LinearLayout. Each of the child LinearLayout should have "android:layout_weight" of 0.5 to cover half the screen
the parent LinearLAyout should have "android:orientation" set to vertical
.
.
here is code for your reference.... this code contains two buttons of height half the screen
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent">
<LinearLayout
android:layout_weight="0.5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:padding="10dp"
android:layout_weight="0.5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="button1"
android:id="@+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
/>
<Button
android:padding="10dp"
android:layout_weight="0.5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="button2"
android:id="@+id/button2"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
/>
</LinearLayout>
<LinearLayout
android:layout_weight="0.5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Here is a bash function for checking if a database exists:
function does_db_exist {
local db="${1}"
local output=$(mysql -s -N -e "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${db}'" information_schema)
if [[ -z "${output}" ]]; then
return 1 # does not exist
else
return 0 # exists
fi
}
Another alternative is to just try to use the database. Note that this checks permission as well:
if mysql "${db}" >/dev/null 2>&1 </dev/null
then
echo "${db} exists (and I have permission to access it)"
else
echo "${db} does not exist (or I do not have permission to access it)"
fi
[[UIDevice currentDevice] uniqueIdentifier]
Returns the Unique ID of your iPhone.
EDIT:
-[UIDevice uniqueIdentifier]
is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.
If you need to create several UUID, just use this method (with ARC):
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string;
}
EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:
NSString *UUID = [[NSUUID UUID] UUIDString];
Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
<T extends ClassA & InterfaceB>
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
Mutex in essence is a lock, providing protected access to shared resources. Under Linux, the thread mutex data type is pthread_mutex_t. Before use, initialize it.
To access to shared resources, you have to lock on the mutex. If the mutex already on the lock, the call will block the thread until the mutex is unlocked. Upon completion of the visit to shared resources, you have to unlock them.
Overall, there are a few unwritten basic principles:
Obtain the lock before using the shared resources.
Holding the lock as short time as possible.
Release the lock if the thread returns an error.
I tried solution based on Laplacian filter from this post. It didn't help me. So, I tried the solution from this post and it was good for my case (but is slow):
import cv2
image = cv2.imread("test.jpeg")
height, width = image.shape[:2]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
def px(x, y):
return int(gray[y, x])
sum = 0
for x in range(width-1):
for y in range(height):
sum += abs(px(x, y) - px(x+1, y))
Less blurred image has maximum sum
value!
You can also tune speed and accuracy by changing step, e.g.
this part
for x in range(width - 1):
you can replace with this one
for x in range(0, width - 1, 10):