Possibly too late to be of benefit now, but is this not the easiest way to do things?
SELECT empName, projIDs = replace
((SELECT Surname AS [data()]
FROM project_members
WHERE empName = a.empName
ORDER BY empName FOR xml path('')), ' ', REQUIRED SEPERATOR)
FROM project_members a
WHERE empName IS NOT NULL
GROUP BY empName
I have been developing and designing iOS apps for a while and This is the best iOS design cheat sheet out there!
have fun :)!
Update: For iOS 8+, and the new devices (iPhone 6, 6 Plus, iPad Air) see this updated link.
Meta update: Iphone 6s/6s Plus have the same resolutions as iPhone 6/6 Plus respectively
This is an image from the new version of the article:
Simply, change
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>
to
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>
ie, add:
data-role="none"
I would like to add that Lin's answer is correct.
If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.
update-database -force
[Use force if necessary]Done, enjoy your new db
UPDATE 11/12/14 - I use this all the time when I make a breaking db change. I found this is a great way to roll back your migrations to the original db:
Run the normal migration to put it back to current
Update-Database -TargetMigration:0 -force
[This will destroy all tables and all data.] Update-Database -force
[use force if necessary]I came to the same conclusion as Dean Perry after much anguish. config.time_zone = 'Adelaide'
and config.active_record.default_timezone = :local
was the winning combination. Here's what I found during the process.
WITHOUT USING JAVASCRIPT
Just add #t=[(start_time), (end_time)]
to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time.
Example:
<video>
<source src="splash.mp4#t=10,20" type="video/mp4">
</video>
Notes: Not supported in IE
Under res -> values ->styles.xml
Change
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
To
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}
.
@click
is just shorthand for v-on:click
directive so the same rules apply.
In your case, simply use @click="addToCount(item.contactID)"
If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.
Command for this is,
ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest
PRIMARY KEY (wardNo, BHTNo, TestID)
<span color="red">red</span>
#!/bin/bash
# convert ansi-colored terminal output to github markdown
# to colorize text on github, we use <span color="red">red</span> etc
# depends on: aha, xclip
# license: CC0-1.0
# note: some tools may need other arguments than `--color=always`
# sample use: colors-to-github.sh diff a.txt b.txt
cmd="$1"
shift
(
echo '<pre>'
$cmd --color=always "$@" 2>&1 | aha --no-header
echo '</pre>'
) \
| sed -E 's/<span style="[^"]*color:([^;"]+);"/<span color="\1"/g' \
| sed -E 's/ style="[^"]*"//g' \
| xclip -i -sel clipboard
trivial :)
I suggest going straight for the model approach in Swing. After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.
If you really want the widget, then you can test each with isSelected
, or maintain a Map<ButtonModel,JRadioButton>
.
Copy paste: •. I've done it with other weird characters, such as ? and ?.
Edit: here's an example. The two Button
s at the bottom have android:text="?"
and "?"
.
I know this is late but it might be of some use:
echo "<pre>";
print_r($array);
echo "</pre>";
well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
And correspondingly, read back to file:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
Make sure they're really tabs! In bash, you can insert a tab using C-v TAB
$ echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED
If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.
Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.
from flask import request
@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
if request.method == "POST":
#perform action here
var value = $('.textbox').val();
$.ajax({
type: 'POST',
url: "{{ url_for('parse_data') }}",
data: JSON.stringify(value),
contentType: 'application/json',
success: function(data){
// do something with the received data
}
});
You can use -
$isTouch = isset($variable);
It will return true
if the $variable
is defined. if the variable is not defined it will return false
.
Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
If you want to check for false
, 0
etc You can then use empty()
-
$isTouch = empty($variable);
empty()
works for -
The answers above are correct, but I thought I would expand another answer by offering a way to do the same if you require to pass parameters into the query.
The SqlDataAdapter
is quick and simple, but only works if you're filling a table with a static request ie: a simple SELECT
without parameters.
Here is my way to do the same, but using a parameter to control the data I require in my table. And I use it to populate a DropDownList
.
//populate the Programs dropdownlist according to the student's study year / preference
DropDownList ddlPrograms = (DropDownList)DetailsView1.FindControl("ddlPrograms");
if (ddlPrograms != null)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ATCNTV1ConnectionString"].ConnectionString))
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProgramID, ProgramName FROM tblPrograms WHERE ProgramCatID > 0 AND ProgramStatusID = (CASE WHEN @StudyYearID = 'VPR' THEN 10 ELSE 7 END) AND ProgramID NOT IN (23,112,113) ORDER BY ProgramName";
cmd.Parameters.Add("@StudyYearID", SqlDbType.Char).Value = "11";
DataTable wsPrograms = new DataTable();
wsPrograms.Load(cmd.ExecuteReader());
//populate the Programs ddl list
ddlPrograms.DataSource = wsPrograms;
ddlPrograms.DataTextField = "ProgramName";
ddlPrograms.DataValueField = "ProgramID";
ddlPrograms.DataBind();
ddlPrograms.Items.Insert(0, new ListItem("<Select Program>", "0"));
}
catch (Exception ex)
{
// Handle the error
}
}
}
Enjoy
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'
Stop recording and you can start inspecting your code.
I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"
Option Explicit
Sub SaveFile()
Dim fdate As Date
Dim fname As String
Dim path As String
fdate = Range("A1").Value
path = Application.ActiveWorkbook.path
If fdate > 0 Then
fname = "Event " & fdate
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
MsgBox "Chose a date for the event", vbOKOnly
End If
End Sub
Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!
After posting the question I thought of the following solution:
We need to check if exactly one of the binary digits is one. So we simply shift the number right one digit at a time, and return true
if it equals 1. If at any point we come by an odd number ((number & 1) == 1
), we know the result is false
. This proved (using a benchmark) slightly faster than the original method for (large) true values and much faster for false or small values.
private static bool IsPowerOfTwo(ulong number)
{
while (number != 0)
{
if (number == 1)
return true;
if ((number & 1) == 1)
// number is an odd number and not 1 - so it's not a power of two.
return false;
number = number >> 1;
}
return false;
}
Of course, Greg's solution is much better.
Unobtrusive Javascript has many many advantages, here are the steps it takes and why it's good to use.
the link loads as normal:
<a id="DaLink" href="http://host/toAnewPage.html">click here</a>
this is important becuase it will work for browsers with javascript not enabled, or if there is an error in the javascript code that doesn't work.
javascript runs on page load:
window.onload = function(){
document.getElementById("DaLink").onclick = function(){
if(funcitonToCall()){
// most important step in this whole process
return false;
}
}
}
if the javascript runs successfully, maybe loading the content in the current page with javascript, the return false cancels the link firing. in other words putting return false has the effect of disabling the link if the javascript ran successfully. While allowing it to run if the javascript does not, making a nice backup so your content gets displayed either way, for search engines and if your code breaks, or is viewed on an non-javascript system.
best book on the subject is "Dom Scription" by Jeremy Keith
express-error-handler lets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for:
var errorHandler = require('express-error-handler'),
handler = errorHandler({
static: {
'404': 'path/to/static/404.html'
}
});
// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );
// Handle all unhandled errors:
app.use( handler );
Or for a custom handler:
handler = errorHandler({
handlers: {
'404': function err404() {
// do some custom thing here...
}
}
});
Or for a custom view:
handler = errorHandler({
views: {
'404': '404.jade'
}
});
Personally, I think a language shouldn't make rules about coding style. It is a matter of preferences, usage, convenience, concept about readability.
Now, a project must set coding rules, for consistency across listings. You might not agree with these rules, but you should stick to them if you want to contribute (or work in a team).
At least, IDEs like Eclispe are agnostic, allowing to set rules like variable prefixes or suffixes, various styles of brace placement and space management, etc. So you can use it to reformat code along your guidelines.
Note: I am among those keeping their old habits from C/C++, coding Java with m_ prefixes for member variables (and s_ for static ones), prefixing booleans with an initial b, using an initial uppercase letter for function names and aligning braces... The horror for Java fundamentalists! ;-)
Funnily, that's the conventions used where I work... probably because the main initial developer comes from MFC world! :-D
The following worked for me.
var temp = ctx.Set<DbTable>()
.GroupBy(g => new { g.id })
.ToDictionary(d => d.Key.id);
I think this code will resolve your issue. Copy and paste this code on your MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener
(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
hideNavigationBar();
}
}
});
}
private void hideNavigationBar() {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
It will works on Android-10. I hope it will helps.
#include <unistd.h>
int usleep(useconds_t useconds); //pass in microseconds
Try this code-
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
It will return user selected timezone.
This is what I used when I stumbled upon this problem.
def order(list_item, i): # reorder at index i
order_at = list_item.index(i)
ordered_list = list_item[order_at:] + list_item[:order_at]
return ordered_list
EX: for the the lowercase letters
order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'
It simply just shifts the list to a specified index
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
ArrayList check = new ArrayList();
for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
check.Add(iValue);
}
I took a slightly different approach than others
static float NextFloat(Random random)
{
double val = random.NextDouble(); // range 0.0 to 1.0
val -= 0.5; // expected range now -0.5 to +0.5
val *= 2; // expected range now -1.0 to +1.0
return float.MaxValue * (float)val;
}
The comments explain what I'm doing. Get the next double, convert that number to a value between -1 and 1 and then multiply that with float.MaxValue
.
function read_file(file, delete_after = false) {
// Code
console.log({file,delete_after});
}
// TEST
read_file("A");
read_file("B",true);
read_file("C",false);
_x000D_
Using the scatter
method of the matplotlib.pyplot
module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1
rather than numpoints=1
in the legend call to have only one point for each legend entry.
In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).
import matplotlib.pyplot as plt
from numpy.random import random
colors = ['b', 'c', 'y', 'm', 'r']
lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])
plt.legend((lo, ll, l, a, h, hh, ho),
('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
scatterpoints=1,
loc='lower left',
ncol=3,
fontsize=8)
plt.show()
To plot a scatter in 3D, use the plot
method, as the legend does not support Patch3DCollection
as is returned by the scatter
method of an Axes3D
instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle
and marker
parameters.
import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D
colors=['b', 'c', 'y', 'm', 'r']
ax = plt.subplot(111, projection='3d')
ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')
plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))
plt.show()
I thought this might be useful:
default-time-zone='+00:00'
To see what value they are set to:
SELECT @@global.time_zone;
To set a value for it use either one:
SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone = '+00:00';
(Using named timezones like 'Europe/Helsinki' means that you have to have a timezone table properly populated.)
Keep in mind that +02:00
is an offset. Europe/Berlin
is a timezone (that has two offsets) and CEST
is a clock time that corresponds to a specific offset.
SELECT @@session.time_zone;
To set it use either one:
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";
Both might return SYSTEM which means that they use the timezone set in my.cnf.
For timezone names to work, you must setup your timezone information tables need to be populated: http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html. I also mention how to populate those tables in this answer.
TIME
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return 02:00:00 if your timezone is +2:00.
SELECT UNIX_TIMESTAMP();
SELECT UNIX_TIMESTAMP(NOW());
SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`
SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`
Note: Changing the timezone will not change the stored datetime or timestamp, but it will show a different datetime for existing timestamp columns as they are internally stored as UTC timestamps and externally displayed in the current MySQL timezone.
I made a cheatsheet here: Should MySQL have its timezone set to UTC?
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
For those of you who came here looking for how to remove an object from a JSON array based on object value:
let users = [{"name": "Ben"},{"name": "Tim"},{"name": "Harry"}];
for (let [i, user] of users.entries()) {
if (user.name == "Tim") {
users.splice(i, 1);
}
}
_x000D_
User Tim is now removed from JSON array users.
Scanf is pretty much always more trouble than it's worth. Here are two better ways to do what you're trying to do. This first one is a more-or-less direct translation of your code. It's longer, but you can look at it and see clearly what it does, unlike with scanf.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char buf[1024], *p, *q;
while (fgets(buf, 1024, stdin))
{
p = buf;
while (*p)
{
while (*p && isspace(*p)) p++;
q = p;
while (*q && !isspace(*q)) q++;
*q = '\0';
if (p != q)
puts(p);
p = q;
}
}
return 0;
}
And here's another version. It's a little harder to see what this does by inspection, but it does not break if a line is longer than 1024 characters, so it's the code I would use in production. (Well, really what I would use in production is tr -s '[:space:]' '\n'
, but this is how you implement something like that.)
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int ch, lastch = '\0';
while ((ch = getchar()) != EOF)
{
if (!isspace(ch))
putchar(ch);
if (!isspace(lastch))
putchar('\n');
lastch = ch;
}
if (lastch != '\0' && !isspace(lastch))
putchar('\n');
return 0;
}
In Ubuntu,
Nginx default root Directory location is /usr/share/nginx/html
The X-Frame-Options is defined in the Http Header and not in the <head>
section of the page you want to use in the iframe.
Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"
Start in the background:
./long_running_process options &
And disown the job before you log out:
disown
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
Funny, I was just researching this yesterday!
I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download
You can also use the jquery prop() method for this.
$(function(){
$('yourselector').prop('target', '_blank');
});
This is from a php script which solves the problem perfectly with every browser I've tested (FF since 3.5, IE8+, Chrome)
header("Content-Disposition: attachment; filename=\"".$fname_local."\"");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fname));
So as far as I can see, you're doing everything correctly. Have you checked your browser settings?
See https://github.com/php-pm/php-pm.
Works fine with symphony.
But I'm fighting with it, trying run a slim app
This worked for me, since none of the other solutions worked for me. NOT EVEN FORCE!
Just had to go through Git Bash
cd REPOSITORY-NAME
git add .
git commit -m "Resolved merge conflict by incorporating both suggestions."
Then back to my cmd and I could: git push heroku master
which in my case was the problem.
I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:
@SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);
One key detail to note is that the propertyName you specify within @BindBeanList
annotation is not same as the column name you pass into the VALUES()
call on update.
If by join you mean union, try this:
set(list(s) + list(t))
It's a bit of a hack, but I can't think of a better one liner to do it.
A filter converting any dates in various ISO-related formats (and who'd use anything else after reading the writings of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:
martind@whitewater:~$ cat `which isoToEpoch`
#!/usr/bin/perl -w
use strict;
use Time::Piece;
# sudo apt-get install libtime-piece-perl
while (<>) {
# date --iso=s:
# 2007-02-15T18:25:42-0800
# Other matched formats:
# 2007-02-15 13:50:29 (UTC-0800)
# 2007-02-15 13:50:29 (UTC-08:00)
s/(\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2})(?:\.\d+)? ?(?:\(UTC)?([+\-]\d{2})?:?00\)?/Time::Piece->strptime ($1, "%Y-%m-%d$2%H:%M:%S")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;
print;
}
martind@whitewater:~$
For the record:
"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".
[HttpPost] is unnecessary!
[Route("")]
public void Post(ProductModel data)
{
...
}
Working with atom (1.21.1 ia32)... i got the same error, even though i added a reference to my pipe in the app.module.ts and in the declarations within app.module.ts
solution was to restart my node instance... stopping the website and then doing ng serve again... going to localhost:4200 worked like a charm after this restart
Use the pattern .
to match any character once, .*
to match any character zero or more times, .+
to match any character one or more times.
It might be a conflict with the same port specified in docker-compose.yml
and docker-compose.override.yml
or the same port specified explicitly and using an environment variable.
I had a docker-compose.yml
with ports on a container specified using environment variables, and a docker-compose.override.yml
with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a
listed neither because the container could not start and list the ports.
Try this instead:
=SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))
It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.
Here's how the formula works.
{1, 1, 1, 2, 2}
.{1, 1, 1, 2, 2}= 1
produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}
, which comprises the condition for the IF statement.{430, 96, 400..
for the values of the sum ranges where the month value equals 1 and ..0,0}
where the month value does not equal 1.{430, 96, 400, 0, 0}
is then summed to get the answer you are looking for.This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.
It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)
--also works.
Heads up: This does not work in Google Spreadsheets
You can use this function
function getParmFromUrl(url, parm) {
var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
var match = url.match(re);
return(match ? match[1] : "");
}
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[\''.$col.'\'],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
Check that:
stateConnectionString="tcpip=server:port"
is correct. Also please check that default port (42424
) is available and your system does not have a firewall
that is blocking the port on your system
source <(curl -s http://mywebsite.com/myscript.txt)
ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash
takes a filename to execute just fine without redirection, and <(command)
syntax provides a path.
bash <(curl -s http://mywebsite.com/myscript.txt)
It may be clearer if you look at the output of echo <(cat /dev/null)
With a little bit correcting @Jolly1234's Answer: here is the code:
raw_string=path.encode('unicode_escape').decode()
You can use CommonCrypto from iOS or CryptoSwift as external library. There are implementations with both tools below. That said, CommonCrypto output with AES should be tested, as it is not clear in CC documentation, which mode of AES it uses.
CommonCrypto in Swift 4.2
import CommonCrypto func encrypt(data: Data) -> Data { return cryptCC(data: data, key: key, operation: kCCEncrypt) } func decrypt(data: Data) -> Data { return cryptCC(data: data, key: key, operation: kCCDecrypt) } private func cryptCC(data: Data, key: String operation: Int) -> Data { guard key.count == kCCKeySizeAES128 else { fatalError("Key size failed!") } var ivBytes: [UInt8] var inBytes: [UInt8] var outLength: Int if operation == kCCEncrypt { ivBytes = [UInt8](repeating: 0, count: kCCBlockSizeAES128) guard kCCSuccess == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else { fatalError("IV creation failed!") } inBytes = Array(data) outLength = data.count + kCCBlockSizeAES128 } else { ivBytes = Array(Array(data).dropLast(data.count - kCCBlockSizeAES128)) inBytes = Array(Array(data).dropFirst(kCCBlockSizeAES128)) outLength = inBytes.count } var outBytes = [UInt8](repeating: 0, count: outLength) var bytesMutated = 0 guard kCCSuccess == CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), Array(key), kCCKeySizeAES128, &ivBytes, &inBytes, inBytes.count, &outBytes, outLength, &bytesMutated) else { fatalError("Cryptography operation \(operation) failed") } var outData = Data(bytes: &outBytes, count: bytesMutated) if operation == kCCEncrypt { ivBytes.append(contentsOf: Array(outData)) outData = Data(bytes: ivBytes) } return outData }
CryptoSwift v0.14 in Swift 4.2
enum Operation { case encrypt case decrypt } private let keySizeAES128 = 16 private let aesBlockSize = 16 func encrypt(data: Data, key: String) -> Data { return crypt(data: data, key: key, operation: .encrypt) } func decrypt(data: Data, key: String) -> Data { return crypt(data: data, key: key, operation: .decrypt) } private func crypt(data: Data, key: String, operation: Operation) -> Data { guard key.count == keySizeAES128 else { fatalError("Key size failed!") } var outData: Data? = nil if operation == .encrypt { var ivBytes = [UInt8](repeating: 0, count: aesBlockSize) guard 0 == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else { fatalError("IV creation failed!") } do { let aes = try AES(key: Array(key.data(using: .utf8)!), blockMode: CBC(iv: ivBytes)) let encrypted = try aes.encrypt(Array(data)) ivBytes.append(contentsOf: encrypted) outData = Data(bytes: ivBytes) } catch { print("Encryption error: \(error)") } } else { let ivBytes = Array(Array(data).dropLast(data.count - aesBlockSize)) let inBytes = Array(Array(data).dropFirst(aesBlockSize)) do { let aes = try AES(key: Array(key.data(using: .utf8)!), blockMode: CBC(iv: ivBytes)) let decrypted = try aes.decrypt(inBytes) outData = Data(bytes: decrypted) } catch { print("Decryption error: \(error)") } } return outData! }
I like Pointy's between
function so I wrote a similar one that worked well for my scenario.
/**
* Checks if an integer is within ±x another integer.
* @param {int} op - The integer in question
* @param {int} target - The integer to compare to
* @param {int} range - the range ±
*/
function nearInt(op, target, range) {
return op < target + range && op > target - range;
}
so if you wanted to see if x
was within ±10 of y
:
var x = 100;
var y = 115;
nearInt(x,y,10) = false
I'm using it for detecting a long-press on mobile:
//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
You can also include this task within another macro, without opening a new one:
I don't put Sub and end Sub, because the macro contains much longer code, as per picture below
With Sheets("1_PL").Range("EF1631:JJ1897")
With .Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
[![enter image description here][1]][1]End With
function go(type, pageCount) {
if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
}
}
Some modern browsers have support for parsing JSON into a native object:
var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);
For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.
I use []
.
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
Invoke-Expression
, also aliased as iex
. The following will work on your examples #2 and #3:
iex $command
Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:
$command = 'C:\somepath\someexe.exe somearg'
iex $command
However, if the exe is in quotes, you need the help of &
to get it running, as in this example, as run from the commandline:
>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"
And then in the script:
$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"
Likely, you could handle nearly all cases by detecting if the first character of the command string is "
, like in this naive implementation:
function myeval($command) {
if ($command[0] -eq '"') { iex "& $command" }
else { iex $command }
}
But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}
, perhaps for specific exception types/messages, or examine the command string.
If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.
Easiest way I find is to:
Right click project
Debug as -> Maven build ...
In the goals field put -Dmaven.surefire.debug test
In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)
Set your breakpoints down and run this configuration and it should hit the breakpoint.
Using the constraints
features UniqueConstraint
is preferred over unique_together.
From the Django documentation for unique_together
:
Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.
For example:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
Simplest is to wrap the image in a center tag, like so ...
<center>![Alt test](http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png)</center>
Anything to do with Markdown can be tested here - http://daringfireball.net/projects/markdown/dingus
Sure, <center>
may be deprecated, but it's simple and it works!
SELECT *
FROM (
SELECT q.*, rownum rn
FROM (
SELECT *
FROM maps006
ORDER BY
id
) q
)
WHERE rn BETWEEN 50 AND 100
Note the double nested view. ROWNUM
is evaluated before ORDER BY
, so it is required for correct numbering.
If you omit ORDER BY
clause, you won't get consistent order.
Are you missing a using directive for System.Linq
?
Change this line
double *ptr = malloc(sizeof(double *) * TIME);
to
double *ptr = malloc(sizeof(double) * TIME);
May be this time stamp fit you better Code
Function LastInputTimeStamp() As Date
LastInputTimeStamp = Now()
End Function
and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this
=IF(C36>0,LastInputTimeStamp(),"")
You need to set left: 0
and right: 0
.
This specifies how far to offset the margin edges from the sides of the window.
Like 'top', but specifies how far a box's right margin edge is offset to the [left/right] of the [right/left] edge of the box's containing block.
Source: http://www.w3.org/TR/CSS2/visuren.html#position-props
Note: The element must have a width smaller than the window or else it will take up the entire width of the window.
If you could use media queries to specify a minimum margin, and then transition to
auto
for larger screen sizes.
.container {_x000D_
left:0;_x000D_
right:0;_x000D_
_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
_x000D_
position: absolute;_x000D_
width: 40%;_x000D_
_x000D_
outline: 1px solid black;_x000D_
background: white;_x000D_
}
_x000D_
<div class="container">_x000D_
Donec ullamcorper nulla non metus auctor fringilla._x000D_
Maecenas faucibus mollis interdum._x000D_
Sed posuere consectetur est at lobortis._x000D_
Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor._x000D_
Sed posuere consectetur est at lobortis._x000D_
</div>
_x000D_
If you can open the http://localhost:8088/cluster but can't open http://localhost:50070/. Maybe datanode didn't start-up or namenode didn't formate.
Hadoop version 2.6.4
check whether your namenode has been formated, if not type:
$ stop-all.sh
$ /path/to/hdfs namenode -format
$ start-all.sh
check your namenode tmp file path, to see in /tmp
, if the namenode directory is in /tmp
, you need set tmp path in core-site.xml
, because every time when you reboot or start your machine, the files in /tmp
will be removed, you need set a tmp dir path.
add the following to it.
<property>
<name>hadoop.tmp.dir</name>
<value>/path/to/hadoop/tmp</value>
</property>
check step 2, stop hadoop and remove the namenode tmp dir in /tmp
, then type /path/to/hdfs namenode -format
, and start the hadoop. The is also a tmp
dir in $HADOOP_HOME
If all the above don't help, please comment below!
I had the same issue. I am having 64 bit windows 8. I downloaded the android studio which worked on 32 bit machine but not on my 64 bit.
The solution for me was pretty simple. I navigated to
C:\Program Files (x86)\Android\android-studio\bin
there I saw 2 exe files studio.exe and studio64.exe. Normally in my start menu was pointing to studio64.exe which alwasys kept on giving me "The enviournmental variable JDK_HOME does not point to valid JVM". So then I clicked studio.exe and it worked :)
I hope this may help someone facing same problem like me
Return a FileResult
or FileStreamResult
from your action, depending on whether the file exists or you create it on the fly.
public ActionResult GetPdf(string filename)
{
return File(filename, "application/pdf", Server.UrlEncode(filename));
}
$watch
returns a deregistration function. Calling it would deregister the $watcher
.
var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
Plenty of responses already, but you can use this:
Sub runQry(qDefName)
Dim db As DAO.Database, qd As QueryDef, par As Parameter
Set db = CurrentDb
Set qd = db.QueryDefs(qDefName)
On Error Resume Next
For Each par In qd.Parameters
Err.Clear
par.Value = Eval(par.Name) 'try evaluating param
If Err.Number <> 0 Then 'failed ?
par.Value = InputBox(par.Name) 'ask for value
End If
Next par
On Error GoTo 0
qd.Execute dbFailOnError
End Sub
Sub runQry_test()
runQry "test" 'qryDef name
End Sub
You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];
var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
return element === array2[index];
});
In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged()
in RunOnUiThread()
.
private void updateData() {
List<Data> newData = getYourNewData();
mAdapter.setList(yourNewList);
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
For current page - window.location.href = "Your url here";
For Parent page - window.top.location.href = "Your url here";
From HTML
<a href="http://someurl" target="_top">link</a>
Type
git push
from the command line inside the repository directory
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
Try using attr.disabled
, instead of disabled
<input [attr.disabled]="disabled ? '' : null"/>
I ran into the same situation where when I copied the formula to another cell the formula was still referencing the cell used in the first formula. To correct this when you set up the rules, select the option "use a formula to determine which cells to format. Then type in the box your formula, for example H23*.25. When you copy the cells down the formulas will change to H24*.25, H25*.25 and so on. Hope this helps.
Simply type in command prompt :
set path=%PATH%;D:\xampp\mysql\bin;
Here my path started from D so I used D: , you can use C: or E:
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
PROJECT eliminates columns while SELECT eliminates rows.
I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id)
function:
$post = Post::find($id);
$post->fill($request->input())->save();
keep in mind that you have to name your inputs with the same column name. The fill()
function will do all the work for you :)
Guess you forgot to append the item to DOM.
Check it HERE.
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World
That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.
Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:
alert($("<p>Hello, <b>World</b></p>").text());
Check out the text method.
Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.
I remove/Rename .gradle
folder in c:\users\Myuser\.gradle
and restart Android Studio and worked for me
You can use the varStatus
attribute like this:-
<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">
myIndex.index will give you the index. Here myIndex
is a LoopTagStatus object.
Hence, you can send that to your javascript method like this:-
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
I know it's a little late response, but I got the same problem a couple of days before and I have came with a nice & smooth solution. First I found this great date picker here
Then I've just updated the CSS class (jquery.calendarPicker.css) that comes with the example like this:
.calMonth {
/*border-bottom: 1px dashed #666;
padding-bottom: 5px;
margin-bottom: 5px;*/
}
.calDay
{
display:none;
}
The plugin fires an event DateChanged when you change anything, so it doesn't matter that you are not clicking on a day (and it fits nice as a year and month picker)
Hope it helps!
In my case a valid provisioning file is because I didn't add the device to the very provisioning file.
The package hash is now available: https://cran.r-project.org/web/packages/hash/hash.pdf
Examples
h <- hash( keys=letters, values=1:26 )
h <- hash( letters, 1:26 )
h$a
# [1] 1
h$foo <- "bar"
h[ "foo" ]
# <hash> containing 1 key-value pair(s).
# foo : bar
h[[ "foo" ]]
# [1] "bar"
It seems that
@Column(name="..")
is completely ignored unless there is
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
specified, so to me this is a bug.
I spent a few hours trying to figure out why @Column(name="..") was ignored.
And you could go the RegExp-way:
var num = "987238";
if(num.match(/^-?\d+$/)){
//valid integer (positive or negative)
}else if(num.match(/^\d+\.\d+$/)){
//valid float
}else{
//not valid number
}
Here is a very simple popup:
<!DOCTYPE html>
<html>
<head>
<style>
#modal {
position:absolute;
background:gray;
padding:8px;
}
#content {
background:white;
padding:20px;
}
#close {
position:absolute;
background:url(close.png);
width:24px;
height:27px;
top:-7px;
right:-7px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var modal = (function(){
// Generate the HTML and add it to the document
$modal = $('<div id="modal"></div>');
$content = $('<div id="content"></div>');
$close = $('<a id="close" href="#"></a>');
$modal.hide();
$modal.append($content, $close);
$(document).ready(function(){
$('body').append($modal);
});
$close.click(function(e){
e.preventDefault();
$modal.hide();
$content.empty();
});
// Open the modal
return function (content) {
$content.html(content);
// Center the modal in the viewport
$modal.css({
top: ($(window).height() - $modal.outerHeight()) / 2,
left: ($(window).width() - $modal.outerWidth()) / 2
});
$modal.show();
};
}());
// Wait until the DOM has loaded before querying the document
$(document).ready(function(){
$('a#popup').click(function(e){
modal("<p>This is popup's content.</p>");
e.preventDefault();
});
});
</script>
</head>
<body>
<a id='popup' href='#'>Simple popup</a>
</body>
</html>
More flexible solution can be found in this tutorial: http://www.jacklmoore.com/notes/jquery-modal-tutorial/ Here's close.png for the sample.
You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.
To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.
DATEPART also works for the time field.
I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.
col_Names=["Sequence", "Start", "End", "Coverage"]
my_CSV_File= pd.read_csv("yourCSVFile.csv",names=col_Names)
having done this, just check it with[well obviously I know, u know that. But still...
my_CSV_File.head()
Hope it helps ... Cheers
$(function() {_x000D_
var wtf = $('#scroll');_x000D_
var height = wtf[0].scrollHeight;_x000D_
wtf.scrollTop(height);_x000D_
});
_x000D_
#scroll {_x000D_
width: 200px;_x000D_
height: 300px;_x000D_
overflow-y: scroll;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="scroll">_x000D_
<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>_x000D_
</div>
_x000D_
Use some javascript!
xmlhttp=new XMLHttpRequest(); xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist) xmlhttp.send("page content goes here");
if (numOptions == 1)
return "if";
else if (numOptions > 2)
return "else if";
else
return "else";
I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.
I modified Sanoj Dushmantha's answer to use sessionStorage instead of localStorage. However, despite the documentation, browsers will still store this data even after the browser is closed. To fix this issue, I am removing the scroll position after it is reset.
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
</script>
&
is HTML for "Start of a character reference".
&
is the character reference for "An ampersand".
¤t;
is not a standard character reference and so is an error (browsers may try to perform error recovery but you should not depend on this).
If you used a character reference for a real character (e.g. ™
) then it (™) would appear in the URL instead of the string you wanted.
(Note that depending on the version of HTML you use, you may have to end a character reference with a ;
, which is why &trade=
will be treated as ™. HTML 4 allows it to be ommited if the next character is a non-word character (such as =
) but some browsers (Hello Internet Explorer) have issues with this).
public class Person{
String s;
Date d;
...
public Person clone(){
Person p = new Person();
p.s = this.s.clone();
p.d = this.d.clone();
...
return p;
}
}
In your executing code:
ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
clone.add(p.clone());
You could also try nextBoolean()
-Method
Here is an example: http://www.tutorialspoint.com/java/util/random_nextboolean.htm
Replace [ with nothing, then ] with nothing.
Perhaps the constructor of MDB2 has some code that uses a $variable =& new ClassName();
No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.
Here is the Python3 code
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
result = set()
nums.sort()
L = len(nums)
for i in range(L):
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,L):
if j > i + 1 and nums[j] == nums[j-1]:
continue
l = j+1
r = L -1
while l <= r:
sum = nums[i] + nums[j] + nums[l]
result.add(sum)
l = l + 1
while l<=r and nums[l] == nums[l-1]:
l = l + 1
result = list(result)
min = result[0]
for i in range(1,len(result)):
if abs(target - result[i]) < abs(target - min):
min = result[i]
return min
You can use the following:
Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
String key = student.stud_location;
if (groupedStudents.get(key) == null) {
groupedStudents.put(key, new ArrayList<Student>());
}
groupedStudents.get(key).add(student);
}
Set<String> groupedStudentsKeySet = groupedCustomer.keySet();
for (String location: groupedStudentsKeySet) {
List<Student> stdnts = groupedStudents.get(location);
for (Student student : stdnts) {
System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
}
}
I recently found out by accident that since you have more control on a ImageView that you can set an onclicklistener for an image here is a sample of a dynamically created image button
private int id;
private bitmap bmp;
LinearLayout.LayoutParams familyimagelayout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT );
final ImageView familyimage = new ImageView(this);
familyimage.setBackground(null);
familyimage.setImageBitmap(bmp);
familyimage.setScaleType(ImageView.ScaleType.FIT_START);
familyimage.setAdjustViewBounds(true);
familyimage.setId(id);
familyimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//what you want to do put here
}
});
For some reason I've never been able to get the Tk solution to work for me. kapace's solution is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version.
import ctypes
OpenClipboard = ctypes.windll.user32.OpenClipboard
EmptyClipboard = ctypes.windll.user32.EmptyClipboard
GetClipboardData = ctypes.windll.user32.GetClipboardData
SetClipboardData = ctypes.windll.user32.SetClipboardData
CloseClipboard = ctypes.windll.user32.CloseClipboard
CF_UNICODETEXT = 13
GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalSize = ctypes.windll.kernel32.GlobalSize
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040
unicode_type = type(u'')
def get():
text = None
OpenClipboard(None)
handle = GetClipboardData(CF_UNICODETEXT)
pcontents = GlobalLock(handle)
size = GlobalSize(handle)
if pcontents and size:
raw_data = ctypes.create_string_buffer(size)
ctypes.memmove(raw_data, pcontents, size)
text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
GlobalUnlock(handle)
CloseClipboard()
return text
def put(s):
if not isinstance(s, unicode_type):
s = s.decode('mbcs')
data = s.encode('utf-16le')
OpenClipboard(None)
EmptyClipboard()
handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
pcontents = GlobalLock(handle)
ctypes.memmove(pcontents, data, len(data))
GlobalUnlock(handle)
SetClipboardData(CF_UNICODETEXT, handle)
CloseClipboard()
paste = get
copy = put
The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 ()
.
When you create a thread, you need an instance of Runnable
. The easiest way to pass in a parameter would be to pass it in as an argument to the constructor:
public class MyRunnable implements Runnable {
private volatile String myParam;
public MyRunnable(String myParam){
this.myParam = myParam;
...
}
public void run(){
// do something with myParam here
...
}
}
MyRunnable myRunnable = new myRunnable("Hello World");
new Thread(myRunnable).start();
If you then want to change the parameter while the thread is running, you can simply add a setter method to your runnable class:
public void setMyParam(String value){
this.myParam = value;
}
Once you have this, you can change the value of the parameter by calling like this:
myRunnable.setMyParam("Goodbye World");
Of course, if you want to trigger an action when the parameter is changed, you will have to use locks, which makes things considerably more complex.
Here is some code for fixing filters. For example, if you turn on filters in your sheet, then you add a column, then you want the new column to also be covered by a filter.
Private Sub AddOrFixFilters()
ActiveSheet.UsedRange.Select
' turn off filters if on, which forces a reset in case some columns weren't covered by the filter
If ActiveSheet.AutoFilterMode Then
Selection.AutoFilter
End If
' turn filters back on, auto-calculating the new columns to filter
Selection.AutoFilter
End Sub
I have removed the scope and then used a maven update to solve this problem.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
**<!-- <scope>provided</scope> -->**
</dependency>
The jstl lib is not present in the tomcat lib folder.So we have to include it. I don't understand why we are told to keep both servlet-api and jstl's scope as provided.
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
I have come across this very useful article about async
and void
written by Jérôme Laban:
https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html
The bottom line is that an async+void
can crash the system and usually should be used only on the UI side event handlers.
The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.
When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.
The PIL distribution is mispackaged for egg installation.
Install Pillow instead, the friendly PIL fork.
One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.
You need to use proper nesting and then apply styles to it.
Right click on button and find the exact class nesting for it using (Inspect element using firebug for firefox), (inspect element for chrome).
Add style to whole bunch of class. Only then it would work
#!/usr/bin/env bash
instead of #!/bin/sh
to prevent the problem caused by /bin/sh
linked to different default shell in different platforms, or there will be error like unexpected operator, that's what happened on my computer (Ubuntu 64 bits 12.04).expr
program unless you install it, so I just use uname
.uname
to get the system information (-s
parameter).expr
and substr
to deal with the string.if
elif
fi
to do the matching job.uname -s
specification.#!/usr/bin/env bash
if [ "$(uname)" == "Darwin" ]; then
# Do something under Mac OS X platform
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
# Do something under GNU/Linux platform
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
# Do something under 32 bits Windows NT platform
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW64_NT" ]; then
# Do something under 64 bits Windows NT platform
fi
The original question was how to tell if a variable was numeric, not if it "has a numeric value".
There are a few operators that have separate modes of operation for numeric and string operands, where "numeric" means anything that was originally a number or was ever used in a numeric context (e.g. in $x = "123"; 0+$x
, before the addition, $x
is a string, afterwards it is considered numeric).
One way to tell is this:
if ( length( do { no warnings "numeric"; $x & "" } ) ) {
print "$x is numeric\n";
}
If the bitwise feature is enabled, that makes &
only a numeric operator and adds a separate string &.
operator, you must disable it:
if ( length( do { no if $] >= 5.022, "feature", "bitwise"; no warnings "numeric"; $x & "" } ) ) {
print "$x is numeric\n";
}
(bitwise is available in perl 5.022 and above, and enabled by default if you use 5.028;
or above.)
The right content type for JSON is application/json
UNLESS you're using JSONP, also known as JSON with Padding, which is actually JavaScript and so the right content type would be application/javascript
.
Classes (or rather their instances) are for representing things. Classes are used to define the operations supported by a particular class of objects (its instances). If your application needs to keep track of people, then Person
is probably a class; the instances of this class represent particular people you are tracking.
Functions are for calculating things. They receive inputs and produce an output and/or have effects.
Classes and functions aren't really alternatives, as they're not for the same things. It doesn't really make sense to consider making a class to "calculate the age of a person given his/her birthday year and the current year". You may or may not have classes to represent any of the concepts of Person
, Age
, Year
, and/or Birthday
. But even if Age
is a class, it shouldn't be thought of as calculating a person's age; rather the calculation of a person's age results in an instance of the Age
class.
If you are modelling people in your application and you have a Person
class, it may make sense to make the age calculation be a method of the Person
class. A method is basically a function which is defined as part of a class; this is how you "define the operations supported by a particular class of objects" as I mentioned earlier.
So you could create a method on your person class for calculating the age of the person (it would probably retrieve the birthday year from the person object and receive the current year as a parameter). But the calculation is still done by a function (just a function that happens to be a method on a class).
Or you could simply create a stand-alone function that receives arguments (either a person object from which to retrieve a birth year, or simply the birth year itself). As you note, this is much simpler if you don't already have a class where this method naturally belongs! You should never create a class simply to hold an operation; if that's all there is to the class then the operation should just be a stand-alone function.
Give the relative path URL value to the pom.xml file
../parentfoldername/pom.xml
For Windows 7:
.jar
C:\Program Files\Java\jre7\bin\javaw.exe
Adapted the solution of @Mike Robins avoiding empty path elements at the beginning:
def parts(path):
p,f = os.path.split(os.path.normpath(path))
return parts(p) + [f] if f and p else [p] if p else []
os.path.normpath()
is actually required only once and could be done in a separate entry function to the recursion.
I know this is a very old question, but from twig 1.6 you can use the slice filter;
{{ myentity.text|slice(0, 50) ~ '...' }}
The second part from the tilde is optional for if you want to add something for example the ellipsis.
Edit: My bad, I see the most up-voted answer do make use of the slice filter.
getline
runnable example
getline
was mentioned on this answer but here is an example.
It is POSIX 7, allocates memory for us, and reuses the allocated buffer on a loop nicely.
Pointer newbs, read this: Why is the first argument of getline a pointer to pointer "char**" instead of "char*"?
main.c
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *line = NULL;
size_t len = 0;
ssize_t read = 0;
while (1) {
puts("enter a line");
read = getline(&line, &len, stdin);
if (read == -1)
break;
printf("line = %s", line);
printf("line length = %zu\n", read);
puts("");
}
free(line);
return 0;
}
Compile and run:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Outcome: this shows on therminal:
enter a line
Then if you type:
asdf
and press enter, this shows up:
line = asdf
line length = 5
followed by another:
enter a line
Or from a pipe to stdin:
printf 'asdf\nqwer\n' | ./main.out
gives:
enter a line
line = asdf
line length = 5
enter a line
line = qwer
line length = 5
enter a line
Tested on Ubuntu 20.04.
glibc implementation
No POSIX? Maybe you want to look at the glibc 2.23 implementation.
It resolves to getdelim
, which is a simple POSIX superset of getline
with an arbitrary line terminator.
It doubles the allocated memory whenever increase is needed, and looks thread-safe.
It requires some macro expansion, but you're unlikely to do much better.
Flagrant Badassery has 11 different trims with benchmark information:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
Non-surprisingly regexp-based are slower than traditional loop.
Here is my personal one. This code is old! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since. (Original used String.charAt)
/**
* Trim string. Actually trims all control characters.
* Ignores fancy Unicode spaces. Forces to string.
*/
function trim(str) {
str = str.toString();
var begin = 0;
var end = str.length - 1;
while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
while (end > begin && str.charCodeAt(end) < 33) { --end; }
return str.substr(begin, end - begin + 1);
}
If you have your radios in a container with id = radioButtonContainerId you can still use onClick and then check which one is selected and accordingly run some functions:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
If you are using the command-line MSBuild command (not the Visual Studio IDE), for example if you are targetting AppVeyor or you just prefer the command line, you can add this option to your MSBuild command line:
/fileLoggerParameters:LogFile=MyLog.log;Append;Verbosity=diagnostic;Encoding=UTF-8
As documented here (warning: usual MSDN verbosity). When the build finishes, search for the string will be compiled
in the log file created during the build, MyLog.log
.
Causes for TypeError: $(…).modal is not a function:
Solutions:
In case, if a script attempt to access an element that hasn't been reached yet then you will get an error. Bootstrap depends on jQuery, so jQuery must be referenced first. So, you must be called the jquery.min.js and then bootstrap.min.js and further the bootstrap Modal error is actually the result of you not including bootstrap's javascript before calling the modal function. Modal is defined in bootstrap.js and not in jQuery. So the script should be included in this manner
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
In case if there are multiple instances of jQuery, the second jQuery
declaration prevents bootstrap.js from working correctly. so make use of
jQuery.noConflict();
before calling the modal popup
jQuery.noConflict();
$('#prizePopup').modal('show');
jQuery event aliases like .load
, .unload
or .error
deprecated since jQuery 1.8.
$(window).on('load', function(){
$('#prizePopup').modal('show');
});
OR try opening the modal popup directly
$('#prizePopup').on('shown.bs.modal', function () {
...
});
use getchar and a while that look like this
while(x = getchar())
{
if(x == '\n'||x == '\0')
do what you need when space or return is detected
else
mystring.append(x)
}
Sorry if I wrote a pseudo-code but I don't work with C language from a while.
Use this:
String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
I was having problem with finding the enhanced uploader tool for uploading folder and subfolders inside it in S3. But rather than finding a tool I could upload the folders along with the subfolders inside it by simply dragging and dropping it in the S3 bucket.
Note: This drag and drop feature doesn't work in Safari. I've tested it in Chrome and it works just fine.
After you drag and drop the files and folders, this screen opens up finally to upload the content.
If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.
This will install an apk directly on the device connected from the aab.
SELECT * FROM `calendar` WHERE startTime like '2010-04-29%'
You can also use comparison operators on MySQL dates if you want to find something after or before. This is because they are written in such a way (largest value to smallest with leading zeros) that a simple string sort will sort them correctly.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat()
function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
Dir
takes wild cards so you could make a big difference adding the filter for test
up front and avoiding testing each file
Sub LoopThroughFiles()
Dim StrFile As String
StrFile = Dir("c:\testfolder\*test*")
Do While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
Loop
End Sub
select min(sal) from (select distinct sal from employee order by sal DESC) where rownum<=N;
place the number whatever the highest sal you want to retrieve.
That error means that jQuery has not yet loaded on the page. Using $(document).ready(...)
or any variant thereof will do no good, as $
is the jQuery function.
Using window.onload
should work here. Note that only one function can be assigned to window.onload
. To avoid losing the original onload logic, you can decorate the original function like so:
originalOnload = window.onload;
window.onload = function() {
if (originalOnload) {
originalOnload();
}
// YOUR JQUERY
};
This will execute the function that was originally assigned to window.onload
, and then will execute // YOUR JQUERY
.
See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.
If I get you right, you need ..\..\src
It is highly unlikely that adding NameVirtualHost *:443
is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).
If you're running a relatively stock Apache configuration, you probably have this somewhere:
<VirtualHost _default_:443>
Your best bet is to either:
VirtualHost
container, or VirtualHost
block and create a new one. Don't forget to include all the relevant SSL options.I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
In my case I added
https://websitename.com/sociallogin/social/callback/?hauth.done=Google
in Authorized redirect URIs
section and it worked for me
A schema and database users are same but if schema has owned database objects and they can do anything their object but user just access the objects, They can't DO any DDL operations until schema user give you the proper privileges.
According to W3C Working Draft 19 November 2013 display
is not an animatable property. Fortunately, visibility
is animatable. You may chain its transition with a transition of opacity (JSFiddle):
HTML:
<a href="http://example.com" id="foo">Foo</a>
<button id="hide-button">Hide</button>
<button id="show-button">Show</button>
CSS:
#foo {
transition-property: visibility, opacity;
transition-duration: 0s, 1s;
}
#foo.hidden {
opacity: 0;
visibility: hidden;
transition-property: opacity, visibility;
transition-duration: 1s, 0s;
transition-delay: 0s, 1s;
}
JavaScript for testing:
var foo = document.getElementById('foo');
document.getElementById('hide-button').onclick = function () {
foo.className = 'hidden';
};
document.getElementById('show-button').onclick = function () {
foo.className = '';
};
Note that if you just make the link transparent, without setting visibility: hidden
, then it would stay clickable.
Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).
To get the actual UTF-8 octets you could use:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
serializer.Serialize(streamWriter, entry);
byte[] utf8EncodedXml = memoryStream.ToArray();
I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var xw = XmlWriter.Create(memStm))
{
serializer.Serialize(xw, entry);
var utf8 = memStm.ToArray();
}
Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.
This is what I would use:
numbers = [float(x)/10 for x in range(10)]
rather than:
numbers = [x*0.1 for x in range(10)]
that would return :
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]
hope it helps.
var result = [];
var arr1 = [1,2,3,4];
var arr2 = [2,3];
arr1.forEach(function(el, idx) {
function unEqual(element, index, array) {
var a = el;
return (element!=a);
}
if (arr2.every(unEqual)) {
result.push(el);
};
});
alert(result);
If you're registering a domain and the termination (ex .com
) it is not IDN, as Aaron Hathaway said:
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org
is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.
The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a
through z
(in a case-insensitive manner), the digits 0
through 9
, and the hyphen -
. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.
Later, Spain with it's .es
, .com.es
, .org.es
, .nom,es
, .gob.es
and .edu.es
introduced IDN tlds, if your tld is one of .es
or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.
If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.
Keep in mind some programs could not work well, especially old, outdated and unpopular ones.
Java String
s aren't character Iterable
. You'll need:
for (int i = 0; i < examplestring.length(); i++) {
char c = examplestring.charAt(i);
...
}
Awkward I know.
toString()
only returns the exception name and the optional message. I would suggest calling
exception.printStackTrace()
to dump the message, or if you need the gory details:
StackTraceElement[] trace = exception.getStackTrace()
The answer is given previous posts is valid. But not one answer is complete with respect to:
- It's NOT a good idea to change this file unless you know what you are doing. It's much better to create a custom.sh shell script in /etc/profile.d/ to make custom changes to your environment, as this will prevent the need for merging in future updates.*
So as stated above create /etc/profile.d/custom.sh file for custom changes.
Now, to always keep updated with newer versions of Java being installed, never put the absolute path, instead use:
#if making jdk as java home
export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")
OR
#if making jre as java home
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:/bin/java::")
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
You can just use the return keyword just like you would in any other function.
Although this is old, it still keeps coming up pretty well in google. So I figured I'd mention this. No one mentioned to check for when x = 0.
0! and 1! both = 1.
This isn't being checked with the previous answers, and would cause a stack overflow, if fact(0) was run. Anyway simple fix:
public static int fact(int x){
if (x==1 | x==0)
return 1;
return fact(x-1) * x;
}// fact
In the possibility that the second page doesn't have shared access to the session cookie, you'll need to set the session cookie path using session_set_cookie_params:
<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
$_SESSION['myvar']='myvalue';
And
<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
echo("1");
if(isset($_SESSION['myvar']))
{
echo("2");
if($_SESSION['myvar'] == 'myvalue')
{
echo("3");
exit;
}
}
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace()
is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g
(global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
You parse the field from the database as usual.
Then let's say you put it in a variable called $title
, you just
<html>
<head>
<title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
</head>
EDIT:
I see your problem. You have to set $title
BEFORE using it. That is, you should query the database before <title>...
I just had to dig through this issue myself and succeeded. Contrary to what others have offered as solutions, the path to my happy ending was directly correlated to JavaDoc. No "src.zip" files necessary. My trials and tribulations in the process involved finding the CORRECT JavaDoc to point at. Pointing a Java 1.7 project at Java 8 Javadoc does NOT work. (Even if "jre8" appears to be the only installed JRE available.) Thus, I beat my head against the brick wall unnecessarily.
Window > Preferences > Java > Installed JREs
If the JRE of your project is not listed (as happened to me when I migrated a jre7 project to a new jre8 workspace), you will need to add it here. Click "Add..." and point your Workspace at the desired jre folder. (Mine was C://Program Files/Java/jre7). Then "Edit..." the now-available JRE, select the rt.jar, and click "Javadoc Location..." and aim it at the correct javadoc location. For my use:
For jre7 -- http://docs.oracle.com/javase/7/docs/api/ For jre8 -- http://docs.oracle.com/javase/8/docs/api/
Voila, hover tooltip javadoc is re-enabled. I hope this helps anyone else trying to figure this problem out.
Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.
class Subscription
def warning_message
<<~HEREDOC
Subscription expiring soon!
Your free trial will expire in #{days_until_expiration} days.
Please update your billing information.
HEREDOC
end
end
Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc
The indentation of the least-indented line will be removed from each line of the content.
To convert tuples to list
(Commas were missing between the tuples in the given question, it was added to prevent error message)
Method 1:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1 = [list(row) for row in level1]
print(level1)
Method 2:
level1 = map(list,level1)
print(list(level1))
Method 1 took --- 0.0019991397857666016 seconds ---
Method 2 took --- 0.0010001659393310547 seconds ---
When I've only needed to specify specific columns, and I want to be explicit, I've used (per DOCS LOCATION):
dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})
So, using the original question, but providing column names to it ...
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
String fname = "Sam\u0025";
PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");
ps.setString(1, fname);
https://3v4l.org/VsQLb Example Here
function listdirs($dir) {
static $alldirs = array();
$dirs = glob($dir . '/*', GLOB_ONLYDIR);
if (count($dirs) > 0) {
foreach ($dirs as $d) $alldirs[] = $d;
}
foreach ($dirs as $dir) listdirs($dir);
return $alldirs;
}
If you change your function definition to use a variable instead:
var get_page = func(url string) string {
...
}
You can override it in your tests:
func TestDownloader(t *testing.T) {
get_page = func(url string) string {
if url != "expected" {
t.Fatal("good message")
}
return "something"
}
downloader()
}
Careful though, your other tests might fail if they test the functionality of the function you override!
The Go authors use this pattern in the Go standard library to insert test hooks into code to make things easier to test:
Microsoft Message Analyzer is the successor of the Microsoft Network Monitor 3.4
If your http incoming traffic is going to your web server at 58000 port, start the Analyzer in Administrator mode and click new session:
use filter: tcp.Port = 58000 and HTTP
trace scenario: "Local Network Interfaces (Win 8 and earlier)" or "Local Network Interfaces (Win 8.1 and later)" depends on your OS
Parsing Level: Full
DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE: sc start MyService
Does the following code work for your problem? I've used a foreach with a bit of linq inside to do the combining of lists and assumed that people are equal if their names match, and it seems to print the expected values out when run. Resharper doesn't offer any suggestions to convert the foreach into linq so this is probably as good as it'll get doing it this way.
public class Person
{
public string Name { get; set; }
public int Value { get; set; }
public int Change { get; set; }
public Person(string name, int value)
{
Name = name;
Value = value;
Change = 0;
}
}
class Program
{
static void Main(string[] args)
{
List<Person> list1 = new List<Person>
{
new Person("a", 1),
new Person("b", 2),
new Person("c", 3),
new Person("d", 4)
};
List<Person> list2 = new List<Person>
{
new Person("a", 4),
new Person("b", 5),
new Person("e", 6),
new Person("f", 7)
};
List<Person> list3 = list2.ToList();
foreach (var person in list1)
{
var existingPerson = list3.FirstOrDefault(x => x.Name == person.Name);
if (existingPerson != null)
{
existingPerson.Change = existingPerson.Value - person.Value;
}
else
{
list3.Add(person);
}
}
foreach (var person in list3)
{
Console.WriteLine("{0} {1} {2} ", person.Name,person.Value,person.Change);
}
Console.Read();
}
}
I don't think it's possible using the for loop syntax. The only thing I can suggest is to do something like:
Collections.reverse(list);
for (Object o : list) {
...
}
... but I wouldn't say this is "cleaner" given that it's going to be less efficient.
You can add one li
element where you want to add divider
<ul>
<li> your content </li>
<li class="divider-vertical-second-menu"></li>
<li> NExt content </li>
<li class="divider-vertical-second-menu"></li>
<li> last item </li>
</ul>
In CSS you can Add following code.
.divider-vertical-second-menu{
height: 40px;
width: 1px;
margin: 0 5px;
overflow: hidden;
background-color: #DDD;
border-right: 2px solid #FFF;
}
This will increase you speed of execution as it will not load any image. just test it out.. :)
Every class has a nil?
method:
if a_variable.nil?
# the variable has a nil value
end
And strings have the empty?
method:
if a_string.empty?
# the string is empty
}
Remember that a string does not equal nil
when it is empty, so use the empty?
method to check if a string is empty.
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
In fact, in R, this operation is very easy:
If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:
a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a
If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:
#for a data.frame:
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b
Note the difference is.nan
when it's a matrix vs. is.na
when it's a data frame.
Doing
#...
b[is.nan(b)] <- 0
#...
yields: Error in is.nan(b) : default method not implemented for type 'list'
because b is a data frame.
Note: Edited for small but confusing typos
It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:
When you update the content of an element with new html using jQuery/javascript, and this new html contains <script>
tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.
You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR
in the console window. (firefox).
It's go to newline then add spaces to start second line at end of first line
Output
Hello
Goodbye
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
return con;
}
<form id="myform">
<input type="textbox" id="field"/>
<input type="button" value="submit">
</form>
<script>
$(function () {
$("#field").keyup(function (event) {
if (event.which === 13) {
document.myform.submit();
}
}
});
</script>
Add the following code in viewDidLoad or loadView
self.navigationController.navigationBar.topItem.title = @"";
I tested it in iPhone and iPad with iOS 9
for all those linux users that are having this problem, check if the rxjs-compat folder is locked. I had this exact same issue and I went in terminal, used the sudo su to give permission to the whole rxjs-compat folder and it was fixed. Thats assuming you imported
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
in the project.ts file where the original .map error occurred.