Modify your $PATH, Add this in your bashrc or bash_profile:
export PATH=/usr/local/bin:/usr/local/sbin:~/bin:$PATH
more click here: Issue #89791
Directly install one of the fink packages (Django 1.6 as of 2013-Nov)
fink install django-py27
fink install django-py33
Or create yourself a virtualenv:
fink install virtualenv-py27
virtualenv django-env
source django-env/bin/activate
pip install django
deactivate # when you are done
Or use fink django plus any other pip installed packages in a virtualenv
fink install django-py27
fink install virtualenv-py27
virtualenv django-env --system-site-packages
source django-env/bin/activate
# django already installed
pip install django-analytical # or anything else you might want
deactivate # back to your normally scheduled programming
I would recommend to use XDoc and XElement of System.Xml.Linq instead of XmlDocument stuff. This would be better and you will be able to make use of the LINQ power in querying and parsing your XML:
Using XElement, your ToXml() method will look like the following:
public XElement ToXml()
{
XElement element = new XElement("Song",
new XElement("Artist", "bla"),
new XElement("Title", "Foo"));
return element;
}
To view the files just browse them from the command prompt (cmd
), eg.:
c:\>cd \Windows\assembly\GAC_32
c:\Windows\assembly\GAC_32> dir
To add and remove files from the GAC use the tool gacutil
we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.
<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />
therefore we use the following snippet
$.validator.addMethod(
"regex",
function(value, element, regstring) {
// fast exit on empty optional
if (this.optional(element)) {
return true;
}
var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
// the parsed pattern had delimiters and modifiers. handle them.
var regexp = new RegExp(regParts[1], regParts[2]);
} else {
// we got pattern string without delimiters
var regexp = new RegExp(regstring);
}
return regexp.test(value);
},
"Please check your input."
);
Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).
PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js
Add an attribute colspan
(abbriviation for 'column span') in your top cell (<td>
) and set its value to 2.
Your table should resembles the following;
<table>
<tr>
<td colspan = "2">
<!-- Merged Columns -->
</td>
</tr>
<tr>
<td>
<!-- Column 1 -->
</td>
<td>
<!-- Column 2 -->
</td>
</tr>
</table>
See also
W3 official docs on HTML Tables
If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec
String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);
Write it as a one-liner:
figure('position', [0, 0, 200, 500]) % create new figure with specified size
This helped me.
#outer {
position:relative;
}
#inner {
position:absolute;
top:0;
left:0px;
right:0px;
height:100%;
}
Change right: and left: to set preferable #inner width.
My problem was the following line (HAML):
%a{"href"=>"#", "ng-click" => "showConfirmDeleteModal()"} Delete
Notice that I have a angular ng-click
and I have an href
tag which will jump to #
which is the same page. I just had to remove the href
tag and I was good to go.
If you want your CSS to be copied into the output without being processed, you can use the (inline)
directive. e.g.,
@import (inline) '../timepicker/jquery.ui.timepicker.css';
The Ubuntu package docker
actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.
The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/
=== UPDATED (thanks @Scott Stensland) ===
You now run the following install script to get docker:
`sudo curl -sSL https://get.docker.com/ | sh`
This will run a script that installs docker. Note the last part of the script:
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:
`sudo usermod -aG docker stens`
Remember that you will have to log out and back in for this to take effect!
To update Docker run:
`sudo apt-get update && sudo apt-get upgrade`
For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below
.
=== UPDATE: For those uncomfortable w/ sudo | sh ===
Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:
sudo apt-get update; \
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88
$ sudo apt-key fingerprint 0EBFCD88
pub rsa4096 2017-02-22 [SCEA]
9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88
uid [ unknown] Docker Release (CE deb) <[email protected]>
sub rsa4096 2017-02-22 [S]
)
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io
If you want to verify that it worked run:
sudo docker run hello-world
The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.
$('#select').on('change', function(){
let element = $("#visiabletoID");
element.val($(this).find(':selected').data('record'));
});
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
the result of opening a file is an iterator, which can be converted to a sequence, which has a length:
with open(filename) as f:
return len(list(f))
this is more concise than your explicit loop, and avoids the enumerate
.
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
From the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip
and msi
).
Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
If you are using Eclipse try Project>clean and then try to restart the server
If you call getcwd it should give you the path:
<?php
echo getcwd();
?>
If your column with DATE datatype has value like below : -
value in column : 10-NOV-2005 06:31:00
Then, You can Use TRUNC function in select query to convert your date-time value to only date like - DD/MM/YYYY or DD-MON-YYYY
select TRUNC(column_1) from table1;
result : 10-NOV-2005
You will see above result - Provided that NLS_DATE_FORMAT is set as like below :-
Alter session NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
If you are using JetBrains Idea IDE (and derivatives) you can select several lines, right click for the context menu, then Git -> Show history for selection. You will see list of commits which were affecting the selected lines:
For Java, consider using Apache Commons FileUtils:
/**
* Convert a file to base64 string representation
*/
public String fileToBase64(File file) throws IOException {
final byte[] bytes = FileUtils.readFileToByteArray(file);
return Base64.getEncoder().encodeToString(bytes);
}
/**
* Convert base64 string representation to a file
*/
public void base64ToFile(String base64String, String filePath) throws IOException {
byte[] bytes = Base64.getDecoder().decode(base64String);
FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
If you want to change style.display
for all nodes loop through the list:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.
Example code:
Activesheet.Range("TableName[ColumnName]").Copy
You can also use :
activesheet.listobjects("TableName[ColumnName]").Copy
You can even use this reference system in worksheet formulas as well. Its very dynamic.
Hope this helps!
You can also use matplotlib for this.
from matplotlib.image import imread
img = imread('abc.tiff')
print(type(img))
output:
<class 'numpy.ndarray'>
I have found that you have to comment out the namespace wrapping the the class at time when moving between version of Visual Studio:
'Namespace FormsAuth
'End Namespace
and at other times, I have to uncomment the namespace.
This happened to me several times when other developers edited the same solution using a different version of VS and/or I moved (copied) the solution to another location
I think no one actually has answered to the first question:
Why did they create those variables?
Those variables aren't strictly necessary. It's true. You can perfectly do something like this:
MONTH_CHOICES = (
("JANUARY", "January"),
("FEBRUARY", "February"),
("MARCH", "March"),
# ....
("DECEMBER", "December"),
)
month = models.CharField(max_length=9,
choices=MONTH_CHOICES,
default="JANUARY")
Why using variables is better? Error prevention and logic separation.
JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)
MONTH_CHOICES = (
(JAN, "January"),
(FEB, "February"),
(MAR, "March"),
# ....
(DEC, "December"),
)
Now, imagine you have a view where you create a new Model instance. Instead of doing this:
new_instance = MyModel(month='JANUARY')
You'll do this:
new_instance = MyModel(month=MyModel.JAN)
In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.
By default ls -t
sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.
For the newest 5 files ordered from newest to oldest, use head
to take the first 5 lines of output:
ls -t | head -n 5
For the newest 5 files ordered from oldest to newest, use the -r
switch to reverse ls
's sort order, and use tail
to take the last 5 lines of output:
ls -tr | tail -n 5
Is there a way to get a list of all the keys in a Go language map?
ks := reflect.ValueOf(m).MapKeys()
how do I iterate over all the keys?
Use the accepted answer:
for k, _ := range m { ... }
Depending upon use case, I would normally use something simple like the following:
abstract class DaysOfWeek
{
const Sunday = 0;
const Monday = 1;
// etc.
}
$today = DaysOfWeek::Sunday;
However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here's an expanded example which may better serve a much wider range of cases:
abstract class BasicEnum {
private static $constCacheArray = NULL;
private static function getConstants() {
if (self::$constCacheArray == NULL) {
self::$constCacheArray = [];
}
$calledClass = get_called_class();
if (!array_key_exists($calledClass, self::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);
self::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return self::$constCacheArray[$calledClass];
}
public static function isValidName($name, $strict = false) {
$constants = self::getConstants();
if ($strict) {
return array_key_exists($name, $constants);
}
$keys = array_map('strtolower', array_keys($constants));
return in_array(strtolower($name), $keys);
}
public static function isValidValue($value, $strict = true) {
$values = array_values(self::getConstants());
return in_array($value, $values, $strict);
}
}
By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:
abstract class DaysOfWeek extends BasicEnum {
const Sunday = 0;
const Monday = 1;
const Tuesday = 2;
const Wednesday = 3;
const Thursday = 4;
const Friday = 5;
const Saturday = 6;
}
DaysOfWeek::isValidName('Humpday'); // false
DaysOfWeek::isValidName('Monday'); // true
DaysOfWeek::isValidName('monday'); // true
DaysOfWeek::isValidName('monday', $strict = true); // false
DaysOfWeek::isValidName(0); // false
DaysOfWeek::isValidValue(0); // true
DaysOfWeek::isValidValue(5); // true
DaysOfWeek::isValidValue(7); // false
DaysOfWeek::isValidValue('Friday'); // false
As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).
Now that most people have finally upgraded to at least 5.3, and SplEnum
is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum
and DaysOfWeek
cannot be instantiated at all, nor should they be.
I am also using nunique
but it will be very helpful if you have to use an aggregate function like 'min', 'max', 'count' or 'mean'
etc.
df.groupby('YEARMONTH')['CLIENTCODE'].transform('nunique') #count(distinct)
df.groupby('YEARMONTH')['CLIENTCODE'].transform('min') #min
df.groupby('YEARMONTH')['CLIENTCODE'].transform('max') #max
df.groupby('YEARMONTH')['CLIENTCODE'].transform('mean') #average
df.groupby('YEARMONTH')['CLIENTCODE'].transform('count') #count
Turns out that the pyspark bin is LOADING python and automatically loading the correct library paths. Check out $SPARK_HOME/bin/pyspark :
# Add the PySpark classes to the Python path:
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
I added this line to my .bashrc file and the modules are now correctly found!
The comment by MK pointed me in the right direction.
In the case of Apache 2.4 and up, there are different defaults and a new directive.
I am running Apache 2.4.6, and I had to add the following directives to get it working:
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
You need to install Xcode from App Store.
Then start Xcode, go to Xcode->Preferences->Downloads
and install component named "Command Line Tools".
After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.
Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script>
but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.
window.onload = () => { //write your code here }
<script src="script.js"></script>
to the bottom of the html file so that it loads last.i think csrf only works with spring forms
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
change to form:form
tag and see it that works.
Official Documentation on facebook developer site:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
The solution was simply that the URI was malformed (because the location of my project was over a "\\" UNC path). This issue was fixed when I used a local workspace.
try document.querySelectorAll("#table td");
If the GridView
(Say the name is gvArchive
) is bound to any DataSource
, the following will clear it:
gvArchive.DataSource = Nothing
gvArchive.DataBind()
Here the code to use your app.js
input specifies file name
res.download(__dirname+'/'+input);
I don't think any of these answers are quite right/optimal. NameValueCollection not only doesn't distinguish between null values and missing values, it's also case-insensitive with regards to it's keys. Thus, I think a full solution would be:
public static bool ContainsKey(this NameValueCollection @this, string key)
{
return @this.Get(key) != null
// I'm using Keys instead of AllKeys because AllKeys, being a mutable array,
// can get out-of-sync if mutated (it weirdly re-syncs when you modify the collection).
// I'm also not 100% sure that OrdinalIgnoreCase is the right comparer to use here.
// The MSDN docs only say that the "default" case-insensitive comparer is used
// but it could be current culture or invariant culture
|| @this.Keys.Cast<string>().Contains(key, StringComparer.OrdinalIgnoreCase);
}
Try this:
$(document).ready(function() {
if ($('#leftmenu').html() === "") {
$('#menuTitleWrapper').remove();
$('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
$('#PageContent').css({'top' : '30px', 'position' : 'relative'});
}
});
It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).
For sending the output to another file (I'm leaving out error checking to focus on the important details):
if (fork() == 0)
{
// child
int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
dup2(fd, 2); // make stderr go to file - you may choose to not do this
// or perhaps send stderr to another file
close(fd); // fd no longer needed - the dup'ed handles are sufficient
exec(...);
}
For sending the output to a pipe so you can then read the output into a buffer:
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
Try it if you get E: Unable to locate package {packageName}
sudo add-apt-repository main
sudo add-apt-repository universe
sudo add-apt-repository restricted
sudo add-apt-repository multiverse
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php-curl
jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent
(see the Special Properties subheading on this page).
I would suggest reading some Microsoft documentation on what you can do with CSOM. This might be one example of what you are looking for, but there is a huge API documented in msdn.
// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");
// Assume that the web has a list named "Announcements".
List announcementsList = context.Web.Lists.GetByTitle("Announcements");
// Assume there is a list item with ID=1.
ListItem listItem = announcementsList.Items.GetById(1);
// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!";
listItem.Update();
context.ExecuteQuery();
If you are looking for a pattern in a directory recursively, you can either first save it to file.
ls -1R ./ | list-of-files.txt
And then grep that, or pipe it to the grep search
ls -1R | grep --color -rE '[A-Z]|'
This will look of listing all files, but colour the ones with uppercase letters. If you remove the last | you will only see the matches.
I use this to find images named badly with upper case for example, but normal grep does not show the path for each file just once per directory so this way I can see context.
If you are using ENUM like MessageStatus, you may need a converter. Just add this class:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* Convert ENUM type in JPA.
*/
@Converter(autoApply = true)
public class MessageStatusConverter implements AttributeConverter<MessageStatus, Integer> {
@Override
public Integer convertToDatabaseColumn(MessageStatus messageStatus) {
return messageStatus.getValue();
}
@Override
public MessageStatus convertToEntityAttribute(Integer i) {
return MessageStatus.valueOf(i);
}
}
Based on MarcGravell's suggestion, I have constructed the following static method.The method generically assigns all matching properties from source object to target using FastMember
public static void DynamicPropertySet(object source, object target)
{
//SOURCE
var src_accessor = TypeAccessor.Create(source.GetType());
if (src_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var src_members = src_accessor.GetMembers();
if (src_members == null)
{
throw new ApplicationException("Could not fetch members!");
}
var src_class_members = src_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var src_class_propNames = src_class_members.Select(x => x.Name);
var src_propNames = src_members.Except(src_class_members).Select(x => x.Name);
//TARGET
var trg_accessor = TypeAccessor.Create(target.GetType());
if (trg_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_members = trg_accessor.GetMembers();
if (trg_members == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_class_members = trg_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var trg_class_propNames = trg_class_members.Select(x => x.Name);
var trg_propNames = trg_members.Except(trg_class_members).Select(x => x.Name);
var class_propNames = trg_class_propNames.Intersect(src_class_propNames);
var propNames = trg_propNames.Intersect(src_propNames);
foreach (var propName in propNames)
{
trg_accessor[target, propName] = src_accessor[source, propName];
}
foreach (var member in class_propNames)
{
var src = src_accessor[source, member];
var trg = trg_accessor[target, member];
if (src != null && trg != null)
{
DynamicPropertySet(src, trg);
}
}
}
An alternative solution without array formulas, possibly more robust than that of a previous answer with a (hint to a) solution without array formulas, is
=INDEX(A:A,INDEX(MAX(($A:$A<>"")*(ROW(A:A))),0))
See this answer as an example. Kudos to Brad and barry houdini, who helped solving this question.
Possible reasons for preferring a non-array formula are given in:
An official Microsoft page (look for "Disadvantages of using array formulas").
Array formulas can seem magical, but they also have some disadvantages:
You have to change the file from .html to .php.
and add this following line
header('Content-Type: text/html; charset=utf-8');
Late to the party, but in case this happens with a WORDPRESS
installation :
#1273 - Unknown collation: 'utf8mb4_unicode_520_ci
In phpmyadmin, under export method
> Format-specific options
( custom export )
Set to : MYSQL40
If you will try to import now, you now might get another error message :
1064 - You have an error in your SQL syntax; .....
That is because The older TYPE
option that was synonymous with ENGINE
was removed in MySQL 5.5.
Open your .sql
file , search and replace all instances
from TYPE=
to ENGINE=
Now the import should go smoothly.
For method decorator declaration
with configuration "noImplicitAny": true,
you can specify type of this variable explicitly depends on @tony19's answer
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button
You render your matplotlib plots to different devices (e.g., on-screen via Quartz versus to to-file via pdf using different functions (plot versus savefig) whose parameters are nearly the same, yet the default values for those parameters are not the same for both functions.
Put another way, the savefig default parameters are different from the default display parameters.
Aligning them is simple if you do it in the matplotlib config file. The template file is included with the source package, and named matplotlibrc.template. If you did not create one when you installed matplotlib, you can get this template from the matplotlib source, or from the matplotlib website.
Once you have customized this file the way you want, rename it to matplotlibrc (no extension) and save it to the directory .matplotlib (note the leading '.') which should be in your home directory.
The config parameters for saving figures begins at about line 314 in the supplied matplotlibrc.template (first line before this section is: ### SAVING FIGURES).
In particular, you will want to look at these:
savefig.dpi : 100 # figure dots per inch
savefig.facecolor : white # figure facecolor when saving
savefig.edgecolor : white # figure edgecolor when saving
savefig.extension : auto # what extension to use for savefig('foo'), or 'auto'
Below these lines are the settings for font type and various image format-specific parameters.
These same parameters for display, i.e., PLT.show(), begin at about line 277 a in the matplotlibrc.template (this section preceded with the line: ### FIGURE):
figure.figsize : 8, 6
figure.dpi : 80
figure.facecolor : 0.75
figure.edgecolor : white
As you can see by comparing the values of these two blocks of parameters, the default settings for the same figure attribute are different for savefig versus display (show).
Changing sender on Gmail / Outlook.com email:
To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.
If you have a limited number of senders you can follow these instructions and then set the From
field to this address: Sending mail from a different address
If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :
msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));
This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.
If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).
Add a type to your variable and then return.
Eg:
const myVariable : string [] = ['hello', 'there'];
const result = myVaraible.map(x=> {
return
{
x.id
}
});
=> Important part is adding the string[] type etc:
cURL is going to be your only real choice here (either that, or using non-blocking sockets and some custom logic).
This link should send you in the right direction. There is no asynchronous processing in PHP, but if you're trying to make multiple simultaneous web requests, cURL multi will take care of that for you.
The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date
, Calendar
, and SimpleDateFormat
.
Parse as a ZonedDateTime
.
String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
.withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
Extract a date-only object, a LocalDate
, without any time-of-day and without any time zone.
LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );
input: Mon Jun 18 00:00:00 IST 2012
zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]
ld: 2012-06-18
output: 18/06/2012
See this code run live in IdeOne.com.
Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.
Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST
may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
To directly answer your two subquestions: No, you cannot do this with Ajax, nor can you calculate it with PHP.
What I have done in the past is use a trigger from the iframe'd page in window.onload
(NOT domready
, as it can take a while for images to load) to pass the page's body height to the parent.
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
Then the parent.resizeIframe
looks like this:
function resizeIframe(newHeight)
{
document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}
Et voila, you have a robust resizer that triggers once the page is fully rendered with no nasty contentdocument
vs contentWindow
fiddling :)
Sure, now people will see your iframe at default height first, but this can be easily handled by hiding your iframe at first and just showing a 'loading' image. Then, when the resizeIframe
function kicks in, put two extra lines in there that will hide the loading image, and show the iframe for that faux Ajax look.
Of course, this only works from the same domain, so you may want to have a proxy PHP script to embed this stuff, and once you go there, you might as well just embed your blog's RSS feed directly into your site with PHP.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","value1");
String query = URLEncodedUtils.format(params, "utf-8");
URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null
HttpGet httpGet = new HttpGet(url);
Note: url = new URI(...)
is buggy
How it looks:
Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:
WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";
outubeWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);
Web view xml code
<WebView
android:id="@+id/youtube_web_view"
android:layout_width="match_parent"
android:layout_height="200dp"/>
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
You can use an object as a map:
var hasName = ({
"true" : "Y",
"false" : "N"
})[name];
This also scales nicely for many options
var hasName = ({
"true" : "Y",
"false" : "N",
"fileNotFound" : "O"
})[name];
(Bonus point for people getting the reference)
Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.
Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.
This fails with the timestamp error:
Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1
This works:
Insert Into Table2
Select Table1.A, Table1.B, null From Table1
I assume you don't want to rebind the event, but call the handler.
You can use trigger()
to trigger events:
$('#billing_state_id').trigger('change');
If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:
function someFunction() {
//do stuff
}
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', someFunction);
$('#click_me').live('click', function() {
//do something
someFunction();
});
});
Also note that live()
is deprecated, on()
is the new hotness.
The checked answer does work but officially in MongooseJS latest, you should use pull.
doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed
https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull
I was just looking that up too.
See Daniel's answer for the correct answer. Much better.
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
You can use pandas.cut
:
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50]
2 100.00 (50, 100]
3 42.12 (25, 50]
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
...and then value_counts
or groupby
and aggregate size
:
s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50] 3
(50, 100] 1
(10, 25] 0
(5, 10] 0
(1, 5] 0
(0, 1] 0
Name: percentage, dtype: int64
s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1] 0
(1, 5] 0
(5, 10] 0
(10, 25] 0
(25, 50] 3
(50, 100] 1
dtype: int64
By default cut
return categorical
.
Series
methods like Series.value_counts()
will use all categories, even if some categories are not present in the data, operations in categorical.
Add System.Web.Extensions as a reference to your project
For Ref.
Check out the GLPaint example.
http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduction/Intro.html
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method. From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
Once upon a time Microsoft, like everyone else, used 7-bit character sets, and they invented their own when it suited them, though they kept ASCII as a core subset. Then they realised the world had moved on to 8-bit encodings and that there were international standards around, such as the ISO-8859 family. In those days, if you wanted to get hold of an international standard and you lived in the US, you bought it from the American National Standards Institute, ANSI, who republished international standards with their own branding and numbers (that's because the US government wants conformance to American standards, not international standards). So Microsoft's copy of ISO-8859 said "ANSI" on the cover. And because Microsoft weren't very used to standards in those days, they didn't realise that ANSI published lots of other standards as well. So they referred to the standards in the ISO-8859 family (and the variants that they invented, because they didn't really understand standards in those days) by the name on the cover, "ANSI", and it found its way into Microsoft user documentation and hence into the user community. That was about 30 years ago, but you still sometimes hear the name today.
It sounds like your error comes from an attempt to run something like this (which works in Linux)
NODE_ENV=development node foo.js
the equivalent in Windows would be
SET NODE_ENV=development
node foo.js
running in the same command shell. You mentioned set NODE_ENV did not work, but wasn't clear how/when you executed it.
If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").
It makes a nice clean list of file names.
Your meta tag should look like this:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
And it has to be placed on the page you want to share (this is unclear in your question).
If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.
Edit the application tag in manifest file.
<application
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
Change the label attribute and give the latest name over there.
In the SVG specification version 1.1 the rendering order is based on the document order:
first element -> "painted" first
Reference to the SVG 1.1. Specification
Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.
You should put the green circle as the latest object to be drawn. So swap the two elements.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120"> _x000D_
<!-- First draw the orange circle -->_x000D_
<circle fill="orange" cx="100" cy="95" r="20"/> _x000D_
_x000D_
<!-- Then draw the green circle over the current canvas -->_x000D_
<circle fill="green" cx="100" cy="105" r="20"/> _x000D_
</svg>
_x000D_
Here the fork of your jsFiddle.
The tag use
with the attribute xlink:href
and as value the id of the element. Keep in mind that might not be the best solution even if the result seems fine. Having a bit of time, here the link of the specification SVG 1.1 "use" Element.
Purpose:
To avoid requiring authors to modify the referenced document to add an ID to the root element.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120">_x000D_
<!-- First draw the green circle -->_x000D_
<circle id="one" fill="green" cx="100" cy="105" r="20" />_x000D_
_x000D_
<!-- Then draw the orange circle over the current canvas -->_x000D_
<circle id="two" fill="orange" cx="100" cy="95" r="20" />_x000D_
_x000D_
<!-- Finally draw again the green circle over the current canvas -->_x000D_
<use xlink:href="#one"/>_x000D_
</svg>
_x000D_
SVG 2 Specification is the next major release and still supports the above features.
Elements in SVG are positioned in three dimensions. In addition to their position on the x and y axis of the SVG viewport, SVG elements are also positioned on the z axis. The position on the z-axis defines the order that they are painted.
Along the z axis, elements are grouped into stacking contexts.
3.4.1. Establishing a stacking context in SVG
...
Stacking contexts are conceptual tools used to describe the order in which elements must be painted one on top of the other when the document is rendered, ...
first up on create your jsp file :
and write the text field which you want
for ex:
after that create your servlet class:
public class test{
protected void doGet(paramter , paramter){
String name = request.getparameter("name");
}
}
Your initial approach was right, but you forgot one little thing about foreach. It doesn't work on the original array/object, but creates a copy of each element as it iterates, so you did unset the copy. Use reference like this:
foreach($doc->seg as &$seg)
{
if($seg['id'] == 'A12')
{
unset($seg);
}
}
The first answer you posted (System is a built-in class...) is pretty spot on.
You can add that the System
class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out
printstream to the native output stream associated with the "standard out" (console).
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
Unless you're looking for something specific, you can already do Regular Expression matching using regular Javascript with strings.
For example, you can do matching using a string by something like this...
var phrase = "This is a phrase";
phrase = phrase.replace(/is/i, "is not");
alert(phrase);
Is there something you're looking for other than just Regular Expression matching in general?
// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());
When adding support for mimetype (as suggested by @ProVega) then it is also best practice to remove the type before adding it - this is to prevent unexpected errors when deploying to servers where support for the type already exists, for example:
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :
// options
$login_email = '[email protected]';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "http://alabala.com/index.php?route=account/login";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";
// begin script
$ch = curl_init();
// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
// execute session to get cookies and required form inputs
$content = curl_exec($ch);
// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;
// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
// perform login
$result = curl_exec($ch);
print $result;
function getFormFields($data)
{
if (preg_match('/()/is', $data, $matches)) {
$inputs = getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
function getInputs($form)
{
$inputs = array();
$elements = preg_match_all("/(]+>)/is", $form, $matches);
if ($elements > 0) {
for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
$grab_url='http://grab.url/alabala';
//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);
var_dump($html);
die;
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.
To fix the 404 error, you need to update your server to serve the index.html
file for each route path you defined.
If you want to switch to the HashBang approach, you need to use this configuration:
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {MyApp} from './myapp';
bootstrap(MyApp, [
ROUTER_PROVIDERS,
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);
In this case, when you refresh the page, it will be displayed again (but you will have a #
in your address).
This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.
Hope it helps you, Thierry
I keep hitting this as a top link for google "ruby for loop", so I wanted to add a solution for loops where the step wasn't simply '1'. For these cases, you can use the 'step' method that exists on Numerics and Date objects. I think this is a close approximation for a 'for' loop.
start = Date.new(2013,06,30)
stop = Date.new(2011,06,30)
# step back in time over two years, one week at a time
start.step(stop, -7).each do |d|
puts d
end
I prefer this
WHERE CASE WHEN my_col LIKE '%val1%' THEN 1
WHEN my_col LIKE '%val2%' THEN 1
WHEN my_col LIKE '%val3%' THEN 1
ELSE 0
END = 1
I'm not saying it's optimal but it works and it's easily understood. Most of my queries are adhoc used once so performance is generally not an issue for me.
You can simplify it to
if ($user_sam -and $user_case) {
...
}
because empty strings coerce to $false
(and so does $null
, for that matter).
The C standard (actually C99, I'm not up to date) says:
Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:
\b
(backspace) Moves the active position to the previous position on the current line. [...]
\t
(horizontal tab) Moves the active position to the next horizontal tabulation position on the current line. [...]
Both just move the active position, neither are supposed to write any character on or over another character. To overwrite with a space you could try: puts("foo\b \tbar");
but note that on some display devices - say a daisy wheel printer - the o
will show the transparent space.
You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
On the server.. In our environment, we're running Apache2 on Windows Server 2003.
Suppose Apache is serving our repository from C:\repo\MyProject
The actual repository is in C:\repo\MyProject\db
and the configuration is in C:\repo\MyProject\conf
So the passwords are in: C:\repo\MyProject.htaccess
They're encrypted, a tool similar to this: http://tools.dynamicdrive.com/password/
new ArrayList<T>(Arrays.asList(myArray));
Make sure that myArray
is the same type as T
. You'll get a compiler error if you try to create a List<Integer>
from an array of int
, for example.
Use Str()
Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display
Select Str(12345.6789, 12, 3)
displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)
for a Total of 12 characters, with 3 to the right of decimal point.
There are correct solutions in the comments, but to summarize them into a single answer:
You have to use DECIMAL(6,4).
Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.
The default formatting is not very useful, in my opinion. I prefer ISO8601 as it's sortable, relatively compact and widely recognized:
>> require 'time'
=> true
>> Time.now.utc.iso8601
=> "2011-07-28T23:14:04Z"
I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:
jQuery UI
has a :data()
selector which can also be used. It has been around since Version 1.7.0 it seems.
You can use it like this:
Get all elements with a data-company
attribute
var companyElements = $("ul:data(group) li:data(company)");
Get all elements where data-company
equals Microsoft
var microsoft = $("ul:data(group) li:data(company)")
.filter(function () {
return $(this).data("company") == "Microsoft";
});
Get all elements where data-company
does not equal Microsoft
var notMicrosoft = $("ul:data(group) li:data(company)")
.filter(function () {
return $(this).data("company") != "Microsoft";
});
etc...
One caveat of the new :data()
selector is that you must set the data
value by code for it to be selected. This means that for the above to work, defining the data
in HTML is not enough. You must first do this:
$("li").first().data("company", "Microsoft");
This is fine for single page applications where you are likely to use $(...).data("datakey", "value")
in this or similar ways.
As far as I'm aware Ratchet is the best PHP WebSocket solution available at the moment. And since it's open source you can see how the author has built this WebSocket solution using PHP.
The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.
From a phylosophic point of view :
An abstract class represents an "is a" relationship. Lets say I have fruits, well I would have a Fruit abstract class that shares common responsabilities and common behavior.
An interface represents a "should do" relationship. An interface, in my opinion (which is the opinion of a junior dev), should be named by an action, or something close to an action, (Sorry, can't find the word, I'm not an english native speaker) lets say IEatable. You know it can be eaten, but you don't know what you eat.
From a coding point of view :
If your objects have duplicated code, it is an indication that they have common behavior, which means you might need an abstract class to reuse the code, which you cannot do with an interface.
Another difference is that an object can implement as many interfaces as you need, but you can only have one abstract class because of the "diamond problem" (check out here to know why! http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem)
I probably forget some points, but I hope it can clarify things.
PS : The "is a"/"should do" is brought by Vivek Vermani's answer, I didn't mean to steal his answer, just to reuse the terms because I liked them!
argc
is the number of arguments being passed into your program from the command line and argv
is the array of arguments.
You can loop through the arguments knowing the number of them like:
for(int i = 0; i < argc; i++)
{
// argv[i] is the argument at index i
}
Translating language codes such as en_US into English (United States) is a built in feature of NSLocale
and NSLocale
does not care where you get the language codes from. So there really is no reason to implement your own translation as the accepted answer suggests.
// Example code - try changing the language codes and see what happens
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSString *l1 = [locale displayNameForKey:NSLocaleIdentifier value:@"en"];
NSString *l2 = [locale displayNameForKey:NSLocaleIdentifier value:@"de"];
NSString *l3 = [locale displayNameForKey:NSLocaleIdentifier value:@"sv"];
NSLog(@"%@, %@, %@", l1, l2, l3);
Prints: English, German, Swedish
I use serializable classes for the WCF communication between different modules. Below is an example of serializable class which serves as DataContract as well. My approach is to use the power of LINQ to convert the Dictionary into out-of-the-box serializable List<> of KeyValuePair<>:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace MyFirm.Common.Data
{
[DataContract]
[Serializable]
public class SerializableClassX
{
// since the Dictionary<> class is not serializable,
// we convert it to the List<KeyValuePair<>>
[XmlIgnore]
public Dictionary<string, int> DictionaryX
{
get
{
return SerializableList == null ?
null :
SerializableList.ToDictionary(item => item.Key, item => item.Value);
}
set
{
SerializableList = value == null ?
null :
value.ToList();
}
}
[DataMember]
[XmlArray("SerializableList")]
[XmlArrayItem("Pair")]
public List<KeyValuePair<string, int>> SerializableList { get; set; }
}
}
The usage is straightforward - I assign a dictionary to my data object's dictionary field - DictionaryX. The serialization is supported inside the SerializableClassX by conversion of the assigned dictionary into the serializable List<> of KeyValuePair<>:
// create my data object
SerializableClassX SerializableObj = new SerializableClassX(param);
// this will call the DictionaryX.set and convert the '
// new Dictionary into SerializableList
SerializableObj.DictionaryX = new Dictionary<string, int>
{
{"Key1", 1},
{"Key2", 2},
};
For basic out of the box python with bs4 installed then you can process your xml with
soup = BeautifulSoup(html, "html5lib")
If however you want to use formatter='xml' then you need to
pip3 install lxml
soup = BeautifulSoup(html, features="xml")
There is also read_csv
in Pandas, which is fast and supports non-comma column separators and automatic typing by column:
import pandas as pd
df = pd.read_csv('your_file',sep='\t')
It can be converted to a NumPy array if you prefer that type with:
import numpy as np
arr = np.array(df)
This is by far the easiest and most mature text import approach I've come across.
I had the same problem and none of suggestions helped. But I found an interesting reason for that, on a physical device, Galaxy Tab.
When USB storage is on, external storage read and write permissions don't have any effect. Just turn off USB storage, and with the correct permissions, you'll have the problem solved.
Both T1
and T2
can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.
See this article for more info.
Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.
And note the pros/cons of using volatile
vs more complex means of sharing state.
Since TypeScript 1.8+
you can use simple simple import
statement like:
import { ClassName } from '../relative/path/to/file';
or the wildcard version:
import * as YourName from 'global-or-relative';
Read more: https://www.typescriptlang.org/docs/handbook/modules.html
Based on the error message, your problem seems to be related to interpolation (typically your expression {{}}
), not to a cross-domain issue. Basically ng-src="{{object.src}}"
sucks.
ng-src
was designed with img
tag in mind IMO. It might not be appropriate for <source>
. See http://docs.angularjs.org/api/ng.directive:ngSrc
If you declare <source src="somesite.com/myvideo.mp4"; type="video/mp4"/>
, it will be working, right? (note that I remove ng-src
in favor of src
) If not it must be fixed first.
Then ensure that {{object.src}}
returns the expected value (outside of <video>
):
<span>{{object.src}}</span>
<video>...</video>
If it returns the expected value, the following statement should be working:
<source src="{{object.src}}"; type="video/mp4"/> //src instead of ng-src
You can just replace like this,
var someString = "23/03/2012";
someString.replace(/\//g, "-");
It works for me..
Just to give a complete answer:
filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
print(image.shape)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
Or if you have a directory of images you can add them all via this Github source file
@mttk and @salvador-dali: I hope it is what you need
Try this
$(function() {
$('input[type="checkbox"]').bind('click',function() {
$('input[type="checkbox"]').not(this).prop("checked", false);
});
});
If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.
What about
lstCountry.Items[lstCountry.SelectedIndex].Text;
Click here this is a good tutorial for both window/ubuntu.
apktool1.5.1.jar download from here.
apktool-install-linux-r05-ibot download from here.
dex2jar-0.0.9.15.zip download from here.
jd-gui-0.3.3.linux.i686.tar.gz (java de-complier) download from here.
framework-res.apk ( Located at your android device /system/framework/)
Procedure:
it will become .zip.
Then extract .zip.
Unzip downloaded dex2jar-0.0.9.15.zip file , copy the contents and paste it to unzip folder.
Open terminal and change directory to unzip “dex2jar-0.0.9.15 “
– cd – sh dex2jar.sh classes.dex (result of this command “classes.dex.dex2jar.jar” will be in your extracted folder itself).
Now, create new folder and copy “classes.dex.dex2jar.jar” into it.
Unzip “jd-gui-0.3.3.linux.i686.zip“ and open up the “Java Decompiler” in full screen mode.
Click on open file and select “classes.dex.dex2jar.jar” into the window.
“Java Decompiler” and go to file > save and save the source in a .zip file.
Create “source_code” folder.
Extract the saved .zip and copy the contents to “source_code” folder.
This will be where we keep your source code.
Extract apktool1.5.1.tar.bz2 , you get apktool.jar
Now, unzip “apktool-install-linux-r05-ibot.zip”
Copy “framework-res.apk” , “.apk” and apktool.jar
Paste it to the unzip “apktool-install-linux-r05-ibot” folder (line no 13).
Then open terminal and type:
– cd
– chown -R : ‘apktool.jar’
– chown -R : ‘apktool’
– chown -R : ‘aapt’
– sudo chmod +x ‘apktool.jar’
– sudo chmod +x ‘apktool’
– sudo chmod +x ‘aapt’
– sudo mv apktool.jar /usr/local/bin
– sudo mv apktool /usr/local/bin
– sudo mv aapt /usr/local/bin
– apktool if framework-res.apk – apktool d .apk
we can create nested cte.please see the below cte in example
;with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)
select * from cte_data,cte_data1
If you want to use base_url()
, so we need to load url helper.
$autoload['helper'] = array('url');
$this->load->helper('url');
Then you can user base_url()
anywhere in controller or view.
In my case this is how I got the information:
find where apache logs are located, and go there, in my case:
cd /var/log/apache2
find in which log openssl information can be found:
grep -i apache.*openssl *_log
e.g. error_log ...
to get fresh information, restart apache, e.g.
rcapache2 restart # or service apache2 restart
check for last entries in the log, e.g.
/var/log/apache2 # tail error_log
[Thu Jun 09 07:42:24 2016] [notice] Apache/... (Linux/...) mod_ssl/2.2.22 OpenSSL/1.0.1t ...
You can use following queries
Users whose Logon Name(Pre-Windows 2000) is equal to John
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(sAMAccountName=**John**))
All Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370))
Enabled Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(!userAccountControl:1.2.840.113556.1.4.803:=2))
Disabled Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(userAccountControl:1.2.840.113556.1.4.803:=2))
LockedOut Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(lockouttime>=1))
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl
+0
.
Your implementation must like:
public boolean equals2(Object object2) {
if(a.equals(object2.a)) {
return true;
}
else return false;
}
With this implementation your both methods would work.
This builds on the answer from kgaidis from https://stackoverflow.com/a/34343418/4316579
I am not sure when the extension stopped working, but at the time of this writing (Swift 4), it appears that the extension will no longer be executed unless you declare UINavigationBarDelegate conformity as described below.
Hope this helps people that are wondering why their extension no longer works.
extension UINavigationController: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
}
}
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]'
, '[^a-zA-Z0-9][^a-zA-Z0-9]'
, ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.
You can use regular expressions.
String input = ...
if (input.matches("[^a-zA-Z0-9 ]"))
If your definition of a 'special character' is simply anything that doesn't apply to your other filters that you already have, then you can simply add an else
. Also note that you have to use else if
in this case:
if(c == ' ') {
blankCount++;
} else if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isLetter(c)) {
letterCount++;
} else {
specialcharCount++;
}
Try this in the CSS of the div:
display: table-cell;
vertical-align: middle;
The simple way to do it is:
UPDATE
table_to_update,
table_info
SET
table_to_update.col1 = table_info.col1,
table_to_update.col2 = table_info.col2
WHERE
table_to_update.ID = table_info.ID
I don't know the reasoning behind this, but I set my parent container to display:flex
and the child containers to display:inline-block
and they stayed inline despite the combined width of the children exceeding the parent.
Didn't need to toy with max-width
, max-height
, white-space
, or anything else.
Hope that helps someone.
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
"Any" works well. Just make sure that the any keyword is on the right side of the equal to sign i.e. is present after the equal to sign.
Below statement will throw error: ERROR: syntax error at or near "any"
select 1 where any('{hello}'::text[]) = 'hello';
Whereas below example works fine
select 1 where 'hello' = any('{hello}'::text[]);
I got this error while connecting to Amazon RDS. I checked the server status 50% of CPU usage while it was a development server and no one is using it.
It was working before, and nothing in the connection configuration has changed. Rebooting the server fixed the issue for me.
The following code will get the date minus timezone offset:
protected Date toGmt0(ZonedDateTime time) {
ZonedDateTime gmt0 = time.minusSeconds(time.getOffset().getTotalSeconds());
return Date.from(gmt0.toInstant());
}
@Test
public void test() {
ZonedDateTime now = ZonedDateTime.now();
Date dateAtSystemZone = Date.from(now.toInstant());
Date dateAtGmt0 = toGmt0(now);
SimpleDateFormat sdfWithoutZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat sdfWithZoneGmt0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ITALIAN);
sdfWithZoneGmt0.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(""
+ "\ndateAtSystemZone = " + dateAtSystemZone
+ "\ndateAtGmt0 = " + dateAtGmt0
+ "\ndiffInMillis = " + (dateAtSystemZone.getTime() - dateAtGmt0.getTime())
+ "\n"
+ "\ndateWithSystemZone.format = " + sdfWithoutZone.format(dateAtSystemZone)
+ "\ndateAtGmt0.format = " + sdfWithoutZone.format(dateAtGmt0)
+ "\n"
+ "\ndateFormatWithGmt0 = " + sdfWithZoneGmt0.format(dateAtSystemZone)
);
output :
dateAtSystemZone = Thu Apr 23 14:03:36 CST 2020
dateAtGmt0 = Thu Apr 23 06:03:36 CST 2020
diffInMillis = 28800000
dateWithSystemZone.format = 2020-04-23 14:03:36.140
dateAtGmt0.format = 2020-04-23 06:03:36.140
dateFormatWithGmt0 = 2020-04-23 06:03:36.140
My system is at GMT+8, so diffInMillis = 28800000 = 8 * 60 * 60 * 1000
?
You can also copy the link address and paste it in a new window to get around the security. This works in chrome and firefox but you may have to add slashes in firefox.
<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>
If you have access to the C++ 11 libraries, check out the std::chrono
library. You can use it to get the milliseconds since the Unix Epoch like this:
#include <chrono>
// ...
using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
I've made a test recently which makes 50000 merge&sort. That means if the string keys are the same, merge the byte string. And the final output should be sorted. So this includes a look up for every insertion.
For the map
implementation, it takes 200 ms to finish the job. For the unordered_map
+ map
, it takes 70 ms for unordered_map
insertion and 80 ms for map
insertion. So the hybrid implementation is 50 ms faster.
We should think twice before we use the map
. If you only need the data to be sorted in the final result of your program, a hybrid solution may be better.
Remove the comma?
select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish'
and a.xyz = b.xyz
Have a look at FROM
SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name
Set is just an interface. In order to retain order, you have to use a specific implementation of that interface and the sub-interface SortedSet, for example TreeSet or LinkedHashSet. You can wrap your Set this way:
Set myOrderedSet = new LinkedHashSet(mySet);
an even simpler solution tested with version 5.2
in your model
// validator rules
public static $rules = array(
...
'email_address' => 'email|required|unique:users,id'
);
This error just means that myapp.views.home
is not something that can be called, like a function. It is a string in fact. While your solution works in django 1.9, nevertheless it throws a warning saying this will deprecate from version 1.10 onwards, which is exactly what has happened. The previous solution by @Alasdair imports the necessary view functions into the script through either
from myapp import views as myapp_views
or
from myapp.views import home, contact
msiexec.exe /x "{588A9A11-1E20-4B91-8817-2D36ACBBBF9F}" /q
Set type=submit
to the button you'd like to be default and type=button
to other buttons. Now in the form below you can hit Enter in any input fields, and the Render
button will work (despite the fact it is the second button in the form).
Example:
<button id='close_button' class='btn btn-success'
type=button>
<span class='glyphicon glyphicon-edit'> </span> Edit program
</button>
<button id='render_button' class='btn btn-primary'
type=submit> <!-- Here we use SUBMIT, not BUTTON -->
<span class='glyphicon glyphicon-send'> </span> Render
</button>
Tested in FF24 and Chrome 35.
I made a pick method like lodash pick. It is not exactly good like lodash _.pick, but you can pick any property event any nested property.
for example:
let car = { name: 'BMW', meta: { model: 2018, color: 'white'};
pick(car,['name','model']) // Output will be {name: 'BMW', model: 2018}
Code :
const pick = (object, props) => {
let newObject = {};
if (isObjectEmpty(object)) return {}; // Object.keys(object).length <= 0;
for (let i = 0; i < props.length; i++) {
Object.keys(object).forEach(key => {
if (key === props[i] && object.hasOwnProperty(props[i])) {
newObject[key] = object[key];
} else if (typeof object[key] === "object") {
Object.assign(newObject, pick(object[key], [props[i]]));
}
});
}
return newObject;
};
function isObjectEmpty(obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) return false;
}
return true;
}
export default pick;
and here is the link to live example with unit tests
The Timer function in VBA gives you the number of seconds elapsed since midnight, to 1/100 of a second.
Dim t as single
t = Timer
'code
MsgBox Timer - t
timestamp is always time in utc, but when you call datetime.datetime.fromtimestamp
it returns you time in your local timezone corresponding to this timestamp, so result depend of your locale.
>>> import time, datetime
>>> time.time()
1564494136.0434234
>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)
There exist nice library arrow
with different behaviour. In same case it returns you time object with UTC timezone.
>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>
When your function is deterministic, you are safe to declare it to be deterministic. The location of "DETERMINISTIC" keyword is as follows.
double i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);
Just create An AnyName.cs file and paste following code.
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Custom
{
static class ConfigurationManager
{
public static IConfiguration AppSetting { get; }
static ConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("YouAppSettingFile.json")
.Build();
}
}
}
Must replace YouAppSettingFile.json file name with your file name.
Your .json file should look like below.
{
"GrandParent_Key" : {
"Parent_Key" : {
"Child_Key" : "value1"
}
},
"Parent_Key" : {
"Child_Key" : "value2"
},
"Child_Key" : "value3"
}
Now you can use it.
Don't forget to Add Reference in your class where you want to use.
using Custom;
Code to retrieve value.
string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = ConfigurationManager.AppSetting["Child_Key"];
It seems you have to use is null
in the HQL, (which can lead to complex permutations if there are more than one parameters with null potential.) but here is a possible solution:
String statusTerm = status==null ? "is null" : "= :status";
String typeTerm = type==null ? "is null" : "= :type";
Query query = getSession().createQuery("from CountryDTO c where c.status " + statusTerm + " and c.type " + typeTerm);
if(status!=null){
query.setParameter("status", status, Hibernate.STRING)
}
if(type!=null){
query.setParameter("type", type, Hibernate.STRING)
}
There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.
I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).
When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.
Maybe some AJAX page content injection could be used as an alternative, though I still can't get around why your teacher would refuse to rid the website of frames.
Additionally, is there any specific reason you personally want to us HTML5?
But if not, I believe <iframe>
s are still around.
You could use this to wrap urllib2:
def URLRequest(url, params, method="GET"):
if method == "POST":
return urllib2.Request(url, data=urllib.urlencode(params))
else:
return urllib2.Request(url + "?" + urllib.urlencode(params))
That will return a Request object that has result data and response codes.
You can easily import your model and run this:
from models import User
# User is the name of table that has a column name
users = User.query.all()
for user in users:
print user.name
None of those worked for me. I was trying to clone a directory from a private git server and entered my credentials false and then it wouldn't let me try different credentials on subsequent tries, it just errored out immediately with an authentication error.
What did work was specifying the user name (mike-wise
)in the url like this:
git clone https://[email protected]/someuser/somerepo.git
To understand get and set, it's all related to how variables are passed between different classes.
The get method is used to obtain or retrieve a particular variable value from a class.
A set value is used to store the variables.
The whole point of the get and set is to retrieve and store the data values accordingly.
What I did in this old project was I had a User class with my get and set methods that I used in my Server class.
The User class's get set methods:
public int getuserID()
{
//getting the userID variable instance
return userID;
}
public String getfirstName()
{
//getting the firstName variable instance
return firstName;
}
public String getlastName()
{
//getting the lastName variable instance
return lastName;
}
public int getage()
{
//getting the age variable instance
return age;
}
public void setuserID(int userID)
{
//setting the userID variable value
this.userID = userID;
}
public void setfirstName(String firstName)
{
//setting the firstName variable text
this.firstName = firstName;
}
public void setlastName(String lastName)
{
//setting the lastName variable text
this.lastName = lastName;
}
public void setage(int age)
{
//setting the age variable value
this.age = age;
}
}
Then this was implemented in the run()
method in my Server class as follows:
//creates user object
User use = new User(userID, firstName, lastName, age);
//Mutator methods to set user objects
use.setuserID(userID);
use.setlastName(lastName);
use.setfirstName(firstName);
use.setage(age);
You can take advantage of the 'npm cache' command which downloads the package tarball and unpacks it into the npm cache directory.
The source can then be copied in.
Using ideas gleaned from https://groups.google.com/forum/?fromgroups=#!topic/npm-/mwLuZZkHkfU I came up with the following node script. No warranties, YMMV, etcetera.
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
util = require('util');
var packageFileName = 'package.json';
var modulesDirName = 'node_modules';
var cacheDirectory = process.cwd();
var npmCacheAddMask = 'npm cache add %s@%s; echo %s';
var sourceDirMask = '%s/%s/%s/package';
var targetDirMask = '%s/node_modules/%s';
function deleteFolder(folder) {
if (fs.existsSync(folder)) {
var files = fs.readdirSync(folder);
files.forEach(function(file) {
file = folder + "/" + file;
if (fs.lstatSync(file).isDirectory()) {
deleteFolder(file);
} else {
fs.unlinkSync(file);
}
});
fs.rmdirSync(folder);
}
}
function downloadSource(folder) {
var packageFile = path.join(folder, packageFileName);
if (fs.existsSync(packageFile)) {
var data = fs.readFileSync(packageFile);
var package = JSON.parse(data);
function getVersion(data) {
var version = data.match(/-([^-]+)\.tgz/);
return version[1];
}
var callback = function(error, stdout, stderr) {
var dependency = stdout.trim();
var version = getVersion(stderr);
var sourceDir = util.format(sourceDirMask, cacheDirectory, dependency, version);
var targetDir = util.format(targetDirMask, folder, dependency);
var modulesDir = folder + '/' + modulesDirName;
if (!fs.existsSync(modulesDir)) {
fs.mkdirSync(modulesDir);
}
fs.renameSync(sourceDir, targetDir);
deleteFolder(cacheDirectory + '/' + dependency);
downloadSource(targetDir);
};
for (dependency in package.dependencies) {
var version = package.dependencies[dependency];
exec(util.format(npmCacheAddMask, dependency, version, dependency), callback);
}
}
}
if (!fs.existsSync(path.join(process.cwd(), packageFileName))) {
console.log(util.format("Unable to find file '%s'.", packageFileName));
process.exit();
}
deleteFolder(path.join(process.cwd(), modulesDirName));
process.env.npm_config_cache = cacheDirectory;
downloadSource(process.cwd());
public static bool MyConcat<T>(ref T[] base_arr, ref T[] add_arr)
{
try
{
int base_size = base_arr.Length;
int size_T = System.Runtime.InteropServices.Marshal.SizeOf(base_arr[0]);
Array.Resize(ref base_arr, base_size + add_arr.Length);
Buffer.BlockCopy(add_arr, 0, base_arr, base_size * size_T, add_arr.Length * size_T);
}
catch (IndexOutOfRangeException ioor)
{
MessageBox.Show(ioor.Message);
return false;
}
return true;
}
You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).
This has nothing to do with function
. Try using a long integer literal instead (as suggested in the other answers).
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
This is what I did. Most tooltip scripts require you to execute a function that stores the tooltips. This is a jQuery example:
$.when($('*').filter(function() {
return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
$(this).attr('title', $(this).text());
}
})).done(function(){
setupTooltip();
});
If you didn't want to check for ellipsis css, you could simplify like:
$.when($('*').filter(function() {
return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
$(this).attr('title', $(this).text());
})).done(function(){
setupTooltip();
});
I have the "when" around it, so that the "setupTooltip" function doesn't execute until all titles have been updated. Replace the "setupTooltip", with your tooltip function and the * with the elements you want to check. * will go through them all if you leave it.
If you simply want to just update the title attributes with the browsers tooltip, you can simplify like:
$('*').filter(function() {
return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
$(this).attr('title', $(this).text());
}
});
Or without check for ellipsis:
$.when($('*').filter(function() {
return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
$(this).attr('title', $(this).text());
});
(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)
Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/
The %~dp0 Variable
The
%~dp0
(that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.The variables
%0-%9
refer to the command line parameters of the batch file.%1-%9
refer to command line arguments after the batch file name.%0
refers to the batch file itself.If you follow the percent character (
%
) with a tilde character (~
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. Thed
modifier expands to the drive letter and thep
modifier expands to the path of the parameter.Example: Let’s say you have a directory on
C:
calledbat_files
, and in that directory is a file calledexample.bat
. In this case,%~dp0
(combining thed
andp
modifiers) will expand toC:\bat_files\
.Check out this Microsoft article for a full explanation.
Also, check out this forum thread.
And a more clear reference from here:
%CmdCmdLine%
will return the entire command line as passed to CMD.EXE
%*
will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
%~dn
will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
%~pn
will return the directory of %n if %n is a valid path or file name (no UNC)
%~nn
will return the file name only of %n if %n is a valid file name
%~xn
will return the file extension only of %n if %n is a valid file name
%~fn
will return the fully qualified path of %n if %n is a valid file name or directory
Just found some good reference for the mysterious ~
tilde operator.
The %~
string is called percent tilde operator. You can find it in situations like: %~0
.
The :~
string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%
.
%1-%9
refer to the command line args. If they are not valid path values, %~dp1
- %~dp9
will all expand to the same value as %~dp0
. But if they are valid path values, they will expand to their own driver/path value.
For example: (batch.bat)
@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on
Run 1:
D:\Workbench>batch arg1 arg2
~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\
Run 2:
D:\Workbench>batch c:\123\a.exe e:\abc\b.exe
~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\
if you want your datetime.now()
precise till the minute , you can use
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
similarly for hour it will be
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')
It is kind of a hack, if someone has a better solution, I am all ears
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
I really like following clean solution.
class Router
include Rails.application.routes.url_helpers
def self.default_url_options
ActionMailer::Base.default_url_options
end
end
router = Router.new
router.posts_url # http://localhost:3000/posts
router.posts_path # /posts
It's from http://hawkins.io/2012/03/generating_urls_whenever_and_wherever_you_want/
Just my two cents for iOS 10 (under NDA, but for people that can use it legally...)
This was tested using Xcode 7.3 (std from Store) AND iPhone 6Plus with 10.0 (14A5261v).
Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.
Finnaly, I find it does not work, if your file content is just copyied like this
foo1=bar;foo2=bar2
I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.
So try this way, it works
curl -H "Cookie:`cat ./my.cookie`" http://xxxx.com
You can just copy the cookie from chrome console network tab.
SET out_number=SQRT(input_number);
Instead of this write:
select SQRT(input_number);
Please don't write SET out_number
and your input parameter should be:
PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT)
You missed in specifying the intent filter elements in your manifest file.Manifest file is:
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="Your Activity Name"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Add and check this correctly. Hope this will help..
For ssh style urls just add ssh before the url:
yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>
versions:update-child-modules
sounds like what you're looking for. You could do versions:set as mentioned, but this is a light-weight way to update the parent version numbers. For the child modules, it's my opinion that you should remove the <version>
definitions, since they will inherit the parent module's version number.
Use the TextBox's Exit
event handler:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Logincode_Click
End Sub
You should use $scope.$apply() when you execute an angular expression from outside of the angular framework.
function countController($scope){
$scope.countDown = 10;
var timer = setInterval(function(){
$scope.countDown--;
$scope.$apply();
console.log($scope.countDown);
}, 1000);
}
You can do that, or you can use the readfile
function, which outputs it for you:
header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();
Edit: Derp, fixed obvious glaring typo.
Merged Chuck Norris's answer w/ Paulo Mendonça's using extensions methods:
/// <summary>
/// Replace a string char at index with another char
/// </summary>
/// <param name="text">string to be replaced</param>
/// <param name="index">position of the char to be replaced</param>
/// <param name="c">replacement char</param>
public static string ReplaceAtIndex(this string text, int index, char c)
{
var stringBuilder = new StringBuilder(text);
stringBuilder[index] = c;
return stringBuilder.ToString();
}
I would use the get_cmap method. Ex.:
import matplotlib.pyplot as plt
plt.imshow(matrix, cmap=plt.get_cmap('gray'))
If you still get this error later after setting the permissions you may need to modify your creation mask. We found our new commits (folders under objects) were still being created with no group write permission, hence only the person who committed them could push into the repository.
We fixed this by setting the umask of the SSH users to 002 with an appropriate group shared by all users.
e.g.
umask 002
where the middle 0 is allowing group write by default.
You are adding the formControlName
to the label and not the input.
You have this:
<div >
<div class="input-field col s12">
<input id="email" type="email">
<label class="center-align" for="email" formControlName="email">Email</label>
</div>
</div>
Try using this:
<div >
<div class="input-field col s12">
<input id="email" type="email" formControlName="email">
<label class="center-align" for="email">Email</label>
</div>
</div>
Update the other input fields as well.
When using forms,we can use 'return false' to prevent submitting.
function checkForm() {
// return true to submit, return false to prevent submitting
}
<form onsubmit="return checkForm()">
...
</form>
Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.
corrected:
SELECT u_name AS user_name FROM users WHERE u_name = 'john';
In bootstrap 4 is easiest.
You can use the classes:
bg-transparent
and border-0
I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();
This is another way to play sound.
An object can only have one prototype. Inheriting from two classes can be done by creating a parent object as a combination of two parent prototypes.
The syntax for subclassing makes it possible to do that in the declaration, since the right-hand side of the extends
clause can be any expression. Thus, you can write a function that combines prototypes according to whatever criteria you like, and call that function in the class declaration.
I had the same problem. Now its working fine after doing below changes.
https://www.google.com/settings/security/lesssecureapps
You should change the "Access for less secure apps" to Enabled (it was enabled, I changed to disabled and than back to enabled). After a while I could send email.
In addition to @Mats answer, I'm adding some more info (it helped me on Debian 8).
My shared folder/clipboard stopped to work for some reason (probably due to a patch installation on my virtual machine).
sudo mount -t vboxsf Shared_Folder ~/SF/
Gave me following result:
VirtualBox: mount.vboxsf: mounting failed with the error: No such device
The solution for me was to stop vboxadd and do a setup after that:
cd /opt/VBoxGuestAdditions-*/init
sudo ./vboxadd setup
At this point, if you still get the following error:
No such device. The Guest Additions installation may have failed. The error has been logged in
/var/log/vboxadd-install.log
You need to install linux headers:
apt-get install linux-headers-$(uname -r)
then you can install Guest Additions:
sh /media/cdrom/VBoxLinuxAdditions.run --nox11
and restart your Linux by:
reboot
then you will be able to mount your shared folder!
mount -t vboxsf Shared_Folder ~/SF/
More informations (in French), check this page.
To save to a file on Windows, OSX and Linux
adb exec-out screencap -p > screen.png
To copy to clipboard on Linux use
adb exec-out screencap -p | xclip -t image/png
var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
arr[i] = ++arr[i];
}
Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.
It appears to only be availabe using the mysqlnd driver.
Try replacing it with the integer it represents; 1002, if I am not mistaken.
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
This does not do what you expect:
if var is 'stringone' or 'stringtwo':
dosomething()
It is the same as:
if (var is 'stringone') or 'stringtwo':
dosomething()
Which is always true, since 'stringtwo'
is considered a "true" value.
There are two alternatives:
if var in ('stringone', 'stringtwo'):
dosomething()
Or you can write separate equality tests,
if var == 'stringone' or var == 'stringtwo':
dosomething()
Don't use is
, because is
compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is
unless you really want object identity.
>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True # but could be False