My solution:
String.prototype.toCapital = function () {
return this.toLowerCase().split(' ').map(function (i) {
if (i.length > 2) {
return i.charAt(0).toUpperCase() + i.substr(1);
}
return i;
}).join(' ');
};
Example:
'álL riGht'.toCapital();
// Returns 'Áll Right'
Here you can find the direct download link for Curl.exe
I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just
unzip it and then go to bin folder there you get exe file
Batch file to copy folder is easy.
xcopy /Y C:\Source\*.* C:\NewFolder
Save the above as a batch file, and get Windows to run it on start up.
To do the same thing when folder is updated is trickier, you'll need a program that monitors the folder every x time and check for changes. You can write the program in VB/Java/whatever then schedule it to run every 30mins.
I very often use regex to extract data from files I just used that to replace the literal quote \"
with //
nothing :-)
cat file.csv | egrep '^\"([0-9]{1,3}\.[0-9]{1,3}\.)' | sed s/\"//g | cut -d, -f1 > list.txt
There are different ways for this:
1.Building C# Applications Using csc.exe
While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.
2.Building .NET Applications Using Notepad++
Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports
3.Building .NET Applications Using SharpDevelop
As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.
I face the same issue. After debug I fixed the same. if the column name in your sql query has multiple times then this issue occur. Hence use alias in sql query to differ the column name. Ex: The below query will work proper in sql query but create issue in SSRS report:
Select P.ID, P.FirstName, P.LastName, D.ID, D.City, D.Area, D.Address From PersonalDetails P Left Join CommunicationDetails D On P.ID = D.PersonalDetailsID
Reason : ID has mentioned twice (Multiple Times)
Correct Query:
Select P.ID As PersonalDetailsID, P.FirstName, P.LastName, D.ID, D.City, D.Area, D.Address From PersonalDetails P Left Join CommunicationDetails D On P.ID = D.PersonalDetailsID
Written in Vanilla Javascript
//Get URL
var loc = window.location.href;
console.log(loc);
var index = loc.indexOf("?");
console.log(loc.substr(index+1));
var splitted = loc.substr(index+1).split('&');
console.log(splitted);
var paramObj = [];
for(var i=0;i<splitted.length;i++){
var params = splitted[i].split('=');
var key = params[0];
var value = params[1];
var obj = {
[key] : value
};
paramObj.push(obj);
}
console.log(paramObj);
//Loop through paramObj to get all the params in query string.
You can pause on any XHR pattern which I find very useful during debugging these kind of scenarios.
For example I have given breakpoint on an URL pattern containing "/"
Don't use exec
. Use spawn
which is an EventEmmiter
object. Then you can listen to stdout
/stderr
events (spawn.stdout.on('data',callback..)
) as they happen.
From NodeJS documentation:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code.toString());
});
exec
buffers the output and usually returns it when the command has finished executing.
You are creating those bytes
objects yourself:
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
Each of those t.encode()
, l.encode()
and d.encode()
calls creates a bytes
string. Do not do this, leave it to the JSON format to serialise these.
Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json
module and the standard file object returned by the open()
call to handle encoding.
You also don't need to convert your items
list to a dictionary; it'll already be an object that can be JSON encoded directly:
class W3SchoolPipeline(object):
def __init__(self):
self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(item) + '\n'
self.file.write(line)
return item
I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape')
it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.
I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.
For me it was that wrong Bits per second value was set.
I'm not sure if you have seen THIS, but Chris Coyier's excellent CSS-Tricks.com posted a link to this a while back and it's a pure CSS solution that accomplishes exactly what you seek.
<div class="ellipsis">
<div>
<p>
Call me Ishmael. Some years ago – never mind how long precisely – having
little or no money in my purse, and nothing particular to interest me on
shore, I thought I would sail about a little and see the watery part of the
world. It is a way I have of driving off the spleen, and regulating the
circulation. Whenever I find myself growing grim about the mouth; whenever it
is a damp, drizzly November in my soul; whenever I find myself involuntarily
pausing before coffin warehouses, and bringing up the rear of every funeral I
meet; and especially whenever my hypos get such an upper hand of me, that it
requires a strong moral principle to prevent me from deliberately stepping
into the street, and methodically knocking people's hats off – then, I account
it high time to get to sea as soon as I can.
</p>
</div>
</div>
html,body,p {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.ellipsis {
overflow: hidden;
height: 200px;
line-height: 25px;
margin: 20px;
border: 5px solid #AAA;
}
.ellipsis:before {
content: "";
float: left;
width: 5px;
height: 200px;
}
.ellipsis > *:first-child {
float: right;
width: 100%;
margin-left: -5px;
}
.ellipsis:after {
content: "\02026";
box-sizing: content-box;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
float: right;
position: relative;
top: -25px;
left: 100%;
width: 3em;
margin-left: -3em;
padding-right: 5px;
text-align: right;
background-size: 100% 100%;/* 512x1 image,gradient for IE9. Transparent at 0% -> white at 50% -> white at 100%.*/
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAABCAMAAACfZeZEAAAABGdBTUEAALGPC/xhBQAAAwBQTFRF////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAA////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wDWRdwAAAP90Uk5TgsRjMZXhS30YrvDUP3Emow1YibnM9+ggOZxrBtpRRo94gxItwLOoX/vsHdA2yGgL8+TdKUK8VFufmHSGgAQWJNc9tk+rb5KMCA8aM0iwpWV6dwP9+fXuFerm3yMs0jDOysY8wr5FTldeoWKabgEJ8RATG+IeIdsn2NUqLjQ3OgBDumC3SbRMsVKsValZplydZpZpbJOQco2KdYeEe36BDAL8/vgHBfr2CvTyDu8R7esU6RcZ5ecc4+Af3iLcJSjZ1ivT0S/PMs3LNck4x8U7wz7Bv0G9RLtHuEq1TbJQr1OtVqqnWqRdoqBhnmSbZ5mXapRtcJGOc4t2eYiFfH9AS7qYlgAAARlJREFUKM9jqK9fEGS7VNrDI2+F/nyB1Z4Fa5UKN4TbbeLY7FW0Tatkp3jp7mj7vXzl+4yrDsYoVx+JYz7mXXNSp/a0RN25JMcLPP8umzRcTZW77tNyk63tdprzXdmO+2ZdD9MFe56Y9z3LUG96mcX02n/CW71JH6Qmf8px/cw77ZvVzB+BCj8D5vxhn/vXZh6D4uzf1rN+Cc347j79q/zUL25TPrJMfG/5LvuNZP8rixeZz/mf+vU+Vut+5NL5gPOeb/sd1dZbTs03hBuvmV5JuaRyMfk849nEM7qnEk6IHI8/qn049hB35QGHiv0yZXuMdkXtYC3ebrglcqvYxoj1muvC1nDlrzJYGbpcdHHIMo2FwYv+j3QAAOBSfkZYITwUAAAAAElFTkSuQmCC);
background: -webkit-gradient(linear,left top,right top,
from(rgba(255,255,255,0)),to(white),color-stop(50%,white));
background: -moz-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
background: -o-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
background: -ms-linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
background: linear-gradient(to right,rgba(255,255,255,0),white 50%,white);
}
Of course, being a pure CSS solution means that it's also a pretty complicated one, but it works cleanly and elegantly. I will assume that Javascript is out of the question because this is much easier to achieve (and arguably more degradable) with Javascript.
As an added bonus, there's a downloadable zip file of the complete process (if you want to understand it and all), but also a SASS mixin file so that you can fold it into your process easy-peasy.
Hope this helps!
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
Contributing to ferrix example,
class Battery():
def __init__(self, battery_size = 60):
self.battery_size = battery_size
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approx " + str(range)
message += "Fully charge"
print(message)
My message will not execute, because none of my conditions are fulfill therefore receiving " UnboundLocalError: local variable 'range' referenced before assignment"
def get_range(self):
if self.battery_size <= 70:
range = 240
elif self.battery_size >= 85:
range = 270
This explains the whole thing:
The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.
The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.
The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.
If your filenames contain no whitepace and you don't have any subdirectories, you can use a simple for
loop:
$ for FILENAME in *; do mv $FILENAME Unix_$FILENAME; done
Otherwise use the convenient rename
command (which is a perl script) - although it might not be available out of the box on every Unix (e.g. OS X doesn't come with rename
).
A short overview at debian-administration.org:
If your filenames contain whitespace it's easier to use find
, on Linux the following should work:
$ find . -type f -name '*' -printf "echo mv '%h/%f' '%h/Unix_%f\n'" | sh
On BSD systems, there is no -printf
option, unfortunately. But GNU findutils should be installable (on e.g. Mac OS X with brew install findutils
).
$ gfind . -type f -name '*' -printf "mv \"%h/%f\" \"%h/Unix_%f\"\n" | sh
To update all possible packages I used conda update --update-all
It works!
There is nothing wrong with syntax of
$('#part' + number).html(text);
jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.
In your case you should pass a String to $()
that is
$(<a string>)
Make sure you have access to the variables number
and text
.
To test do:
function(){
alert(number + ":" + text);//or use console.log(number + ":" + text)
$('#part' + number).html(text);
});
If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.
String(format: "%.2f", Double(round(1000*34.578)/1000))
Output: 34.58
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server
For specific versions, such as mysql-server-5.6
, you'll need to specify the version in like this:
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6
For mysql-community-server, the keys are slightly different:
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server
Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)
If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:
echo ... | sudo debconf-set-selections
I am not sure if that is what OP meant, but I came across this question because I was searching for a list of issues I have to keep in mind when migrating from Underscore.js to Lodash.
I would really appreciate if someone posted an article with a complete list of such differences. Let me start with the things I've learned the hard way (that is, things which made my code explode on production:/):
_.flatten
in Underscore.js is deep by default, and you have to pass true as second argument to make it shallow. In Lodash it is shallow by default and passing true as second argument will make it deep! :)_.last
in Underscore.js accepts a second argument which tells how many elements you want. In Lodash there is no such option. You can emulate this with .slice
_.first
(same issue)_.template
in Underscore.js can be used in many ways, one of which is providing the template string and data and getting HTML back (or at least that's how it worked some time ago). In Lodash you receive a function which you should then feed with the data._(something).map(foo)
works in Underscore.js, but in Lodash I had to rewrite it to _.map(something,foo)
. Perhaps that was just a TypeScript
-issue.foreach (DataGridViewRow row in GridView2.Rows)
{
if ( ! row.IsNewRow)
{
for (int i = 0; i < GridView2.Columns.Count; i++)
{
String header = GridView2.Columns[i].HeaderText;
String cellText = Convert.ToString(row.Cells[i].Value);
}
}
}
Here Before Iterating for cell Values need to check for NewRow.
Arrrgh! Faced this on macOS today and the issue was as simple as - the pop-up window suggesting to install the new Appium version was showing on the remote CI build server.
Just VNC'ing to it and clicking "Install later" fixed it.
You can use the isin
method on the date
column like so
df[df["date"].isin(pd.date_range(start_date, end_date))]
Note: This only works with dates (as the question asks) and not timestamps.
Example:
import numpy as np
import pandas as pd
# Make a DataFrame with dates and random numbers
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
# Select the rows between two dates
in_range_df = df[df["date"].isin(pd.date_range("2017-01-15", "2017-01-20"))]
print(in_range_df) # print result
which gives
0 1 2 date
14 0.960974 0.144271 0.839593 2017-01-15
15 0.814376 0.723757 0.047840 2017-01-16
16 0.911854 0.123130 0.120995 2017-01-17
17 0.505804 0.416935 0.928514 2017-01-18
18 0.204869 0.708258 0.170792 2017-01-19
19 0.014389 0.214510 0.045201 2017-01-20
Instead of changing the user, I've found this advise:
This might help someone else out - after trying every solution to trying and fix this error on SQL 64..
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
..I found an article here...
http://sqlserverpedia.com/blog/sql-server-bloggers/too-many-bits/
..which suggested I give Everyone full permission on this folder..
C:\Users\SQL Service account name\AppData\Local\Temp
And hey presto! My query suddenly burst into life. I punched the air in delight.
Edwaldo
Well, I do my coding in NetBeans 8.1:
First: Create a new project, select Java application and name your project.
Then modify your code after public class to look like the following:
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
try (Scanner scanner = new Scanner(new File("C:\\Users\\YourName\\Folder\\file.csv"))) {
scanner.useDelimiter(",");
while(scanner.hasNext()){
System.out.print(scanner.next()+"|");
}}
}
}
Try using Ctrl-click on the multiple places you want the cursors. Ctrl-D is for multiple incremental finds.
Here it is as a single formula:
=(RIGHT(D2,3))+(MID(D2,7,2)*1000)+(MID(D2,4,2)*60000)+(LEFT(D2,2)*3600000)
There are 2 possibilities.
You really don't have Label
property.
You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance
If your property is not public, you will need to use BindingFlags.NonPublic
or some other combination of flags which fits your use case. Read the referenced API docs to find the details.
EDIT:
ooops, just noticed you call GetProperty
on typeof(MyClass)
. typeof(MyClass)
is Type
which for sure has no Label
property.
There's not a way as of 11/2012, HOWEVER
Highlight Text (In visual Studio.net)
ctrl + k + c, ctrl + k + u
Will comment / uncomment, respectively
In a plain a SQL-Developer installation under Windows go to directory
C:\Program Files\sqldeveloper\sqldeveloper\bin
and add
AddVMOption -Duser.timezone=CET
to file sqldeveloper.conf
.
Add a line getchar();
or system("pause");
before your return 0;
in main function.
It will work for you.
On CentOS, just run rm linkname
and it will ask to "remove symbolic link?". Type Y and Enter, the link will be gone and the directory be safe.
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login -i
Git bash will get open.
i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?
do:
getchar();
before the end of the program
The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.
There are at least two ways to solve this.
Solution 1:
If you are okay with using an absolutely positioned element, you can use the top
and bottom
properties instead of height
. By setting both top
and bottom
to 0
you force the element into taking up full height.
#menu
{
position: absolute;
border-right: 1px solid black;
top: 0;
bottom: 0;
}?
Solution 2:
Another way would be to force the HTML and BODY elements into a 100% height, to give room for a menu with 100% height:
body, html { height: 100%; }
#menu
{
border-right: 1px solid black;
height: 100%;
}?
To summarize the above post by Cheers and hth. - Alf, Make sure you have main()
or WinMain()
defined and g++ should do the right thing.
My problem was that main()
was defined inside of a namespace by accident.
Not sure why it's doing that. Try -s
with the -o
option to set the output file instead of >
.
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5. Happy coding!
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
This thread has a good discussion and a useful solution:
function pause( iMilliseconds )
{
var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}
Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.
another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Main()
{
InitializeComponent();
Process current = Process.GetCurrentProcess();
string currentmd5 = md5hash(current.MainModule.FileName);
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (process.Id != current.Id)
{
try
{
if (currentmd5 == md5hash(process.MainModule.FileName))
{
SetForegroundWindow(process.MainWindowHandle);
Environment.Exit(0);
}
}
catch (/* your exception */) { /* your exception goes here */ }
}
}
}
private string md5hash(string file)
{
string check;
using (FileStream FileCheck = File.OpenRead(file))
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5Hash = md5.ComputeHash(FileCheck);
check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
}
return check;
}
it checks only md5 sums by process id.
if an instance of this application was found, it focuses the running application and exit itself.
you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.
may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.
For Formatting in mm-dd-yyyy
aa=date.split("-")
date=aa[1]+'-'+aa[2]+'-'+aa[0]
Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.
Note: This answer predates the Unicode requirement; see the comments.
Just cast it:
CString s;
const TCHAR* x = (LPCTSTR) s;
It works because CString has a cast operator to do exactly this.
Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char
instead of TCHAR
.
You need to install psycopg2
Python library.
Download http://initd.org/psycopg/, then install it under Python PATH
After downloading, easily extract the tarball and:
$ python setup.py install
Or if you wish, install it by either easy_install or pip.
(I prefer to use pip over easy_install for no reason.)
$ easy_install psycopg2
$ pip install psycopg2
in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'db_name',
'USER': 'db_user',
'PASSWORD': 'db_user_password',
'HOST': '',
'PORT': 'db_port_number',
}
}
- Other installation instructions can be found at download page and install page.
For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri()
instead of RingtoneManager.getDefaultUri()
. According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri()
:
Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.
Meanwhile getDefaultUri()
says this:
Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.
Just make a rule for each case:
<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1) }">
Or use the ternary operator:
<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">
I am using git-bash in windows.The simplest way is to change the path address to have the forward slashes:
git clone C:/Dev/proposed
P.S: Start the git-bash on the destination folder.
Path used in clone ---> c:/Dev/proposed
Original path in windows ---> c:\Dev\proposed
Here's my PowerShell Send-MailMessage sample for Gmail...
Tested and working solution:
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Just change $EmailTo, and username/password in $SMTPClient.Credentials... Do not include @gmail.com in your username...
GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.
A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.
http://developer.android.com/guide/topics/location/obtaining-user-location.html
Do the following steps:
npm install --save bootstrap
And in your .angular-cli.json, add to styles section:
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.css"]
After that, you must restart your ng serve
Enjoy
This did wonders for me:
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
if (top != self) {
top.location.replace(location);
location.replace("about:blank"); // want me framed? no way!
}
DECLARE @CarList nvarchar(max);
SET @CarList = N'';
SELECT @CarList+=CarName+N','
FROM dbo.CARS;
SELECT LEFT(@CarList,LEN(@CarList)-1);
Thanks are due to whoever on SO showed me the use of accumulating data during a query.
This category may be to your taste. But! Be frugal with its usage; since we are converting to a NSMutableArray and back again, it's not at all efficient.
@implementation NSArray (mxcl)
- (NSArray *)arrayByRemovingObject:(id)obj
{
if (!obj) return [self copy]; // copy because all array* methods return new arrays
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:self];
[mutableArray removeObject:obj];
return [NSArray arrayWithArray:mutableArray];
}
@end
Please try this
SELECT *
FROM [Village]
WHERE CONVERT(VARCHAR, CastleType) = 'foo'
From Overview of Numeric Types;
BIT[(M)]
A bit-field type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M is omitted.
This data type was added in MySQL 5.0.3 for MyISAM, and extended in 5.0.5 to MEMORY, InnoDB, BDB, and NDBCLUSTER. Before 5.0.3, BIT is a synonym for TINYINT(1).
TINYINT[(M)] [UNSIGNED] [ZEROFILL]
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
Additionally consider this;
BOOL, BOOLEAN
These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
For Xcode 7, un-ticking the 'translucent' check mark for the Navigation Bar worked for me.
Not difficult, check this.
<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
Static NSString *CellIdentifier = @"Cell";
QTStaffViewCell *cell = (QTStaffViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
If (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QTStaffViewCell" owner:self options:nil];
cell = [nib objectAtIndex: 0];
}
StaffData = [self.staffArray objectAtIndex:indexPath.row];
NSString *title = StaffData.title;
NSString *fName = StaffData.firstname;
NSString *lName = StaffData.lastname;
UIFont *FedSanDemi = [UIFont fontWithName:@"Aller" size:18];
cell.drName.text = [NSString stringWithFormat:@"%@ %@ %@", title,fName,lName];
[cell.drName setFont:FedSanDemi];
UIFont *aller = [UIFont fontWithName:@"Aller" size:14];
cell.drJob.text = StaffData.job;
[cell.drJob setFont:aller];
if ([StaffData.title isEqualToString:@"Dr"])
{
cell.drJob.frame = CGRectMake(83, 26, 227, 40);
}
else
{
cell.drJob.frame = CGRectMake(90, 26, 227, 40);
}
if ([StaffData.staffPhoto isKindOfClass:[NSString class]])
{
NSURL *url = [NSURL URLWithString:StaffData.staffPhoto];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url
completionHandler:^(NSURL *location,NSURLResponse *response, NSError *error) {
NSData *imageData = [NSData dataWithContentsOfURL:location];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_sync(dispatch_get_main_queue(),
^{
cell.imageView.image = image;
});
}];
[task resume];
}
return cell;}
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
To add to the above answers, ensure you define your function like this:
public function functionName(Request $request) {
//
}
Note the "(Request $request)", now set a session like this:
$request->session()->put('key', 'value');
And retrieve the session in this way:
$data = $request->session()->get('key');
To erase the session try this:
$request->session()->forget('key');
or
$request->session()->flush();
Since there is discussion about performance I figured I'd add in a comparison that included StringBuilder. It is in fact faster than the concat and, naturally the String.format option.
To make this a sort of apples to apples comparison I instantiate a new StringBuilder in the loop rather than outside (this is actually faster than doing just one instantiation most likely due to the overhead of re-allocating space for the looping append at the end of one builder).
String formatString = "Hi %s; Hi to you %s";
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format(formatString, i, +i * 2);
}
long end = System.currentTimeMillis();
log.info("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
end = System.currentTimeMillis();
log.info("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder bldString = new StringBuilder("Hi ");
bldString.append(i).append("; Hi to you ").append(i * 2);
}
end = System.currentTimeMillis();
log.info("String Builder = " + ((end - start)) + " millisecond");
fetch("http://localhost:8988/api", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then((response) =>response.json());
.then((data) => {
console.log(data);
})
.catch(error => {
return error;
});
SQL Server 2008 And Up
Just filter a unique index:
CREATE UNIQUE NONCLUSTERED INDEX UQ_Party_SamAccountName
ON dbo.Party(SamAccountName)
WHERE SamAccountName IS NOT NULL;
In Lower Versions, A Materialized View Is Still Not Required
For SQL Server 2005 and earlier, you can do it without a view. I just added a unique constraint like you're asking for to one of my tables. Given that I want uniqueness in column SamAccountName
, but I want to allow multiple NULLs, I used a materialized column rather than a materialized view:
ALTER TABLE dbo.Party ADD SamAccountNameUnique
AS (Coalesce(SamAccountName, Convert(varchar(11), PartyID)))
ALTER TABLE dbo.Party ADD CONSTRAINT UQ_Party_SamAccountName
UNIQUE (SamAccountNameUnique)
You simply have to put something in the computed column that will be guaranteed unique across the whole table when the actual desired unique column is NULL. In this case, PartyID
is an identity column and being numeric will never match any SamAccountName
, so it worked for me. You can try your own method—be sure you understand the domain of your data so that there is no possibility of intersection with real data. That could be as simple as prepending a differentiator character like this:
Coalesce('n' + SamAccountName, 'p' + Convert(varchar(11), PartyID))
Even if PartyID
became non-numeric someday and could coincide with a SamAccountName
, now it won't matter.
Note that the presence of an index including the computed column implicitly causes each expression result to be saved to disk with the other data in the table, which DOES take additional disk space.
Note that if you don't want an index, you can still save CPU by making the expression be precalculated to disk by adding the keyword PERSISTED
to the end of the column expression definition.
In SQL Server 2008 and up, definitely use the filtered solution instead if you possibly can!
Controversy
Please note that some database professionals will see this as a case of "surrogate NULLs", which definitely have problems (mostly due to issues around trying to determine when something is a real value or a surrogate value for missing data; there can also be issues with the number of non-NULL surrogate values multiplying like crazy).
However, I believe this case is different. The computed column I'm adding will never be used to determine anything. It has no meaning of itself, and encodes no information that isn't already found separately in other, properly defined columns. It should never be selected or used.
So, my story is that this is not a surrogate NULL, and I'm sticking to it! Since we don't actually want the non-NULL value for any purpose other than to trick the UNIQUE
index to ignore NULLs, our use case has none of the problems that arise with normal surrogate NULL creation.
All that said, I have no problem with using an indexed view instead—but it brings some issues with it such as the requirement of using SCHEMABINDING
. Have fun adding a new column to your base table (you'll at minimum have to drop the index, and then drop the view or alter the view to not be schema bound). See the full (long) list of requirements for creating an indexed view in SQL Server (2005) (also later versions), (2000).
Update
If your column is numeric, there may be the challenge of ensuring that the unique constraint using Coalesce
does not result in collisions. In that case, there are some options. One might be to use a negative number, to put the "surrogate NULLs" only in the negative range, and the "real values" only in the positive range. Alternately, the following pattern could be used. In table Issue
(where IssueID
is the PRIMARY KEY
), there may or may not be a TicketID
, but if there is one, it must be unique.
ALTER TABLE dbo.Issue ADD TicketUnique
AS (CASE WHEN TicketID IS NULL THEN IssueID END);
ALTER TABLE dbo.Issue ADD CONSTRAINT UQ_Issue_Ticket_AllowNull
UNIQUE (TicketID, TicketUnique);
If IssueID 1 has ticket 123, the UNIQUE
constraint will be on values (123, NULL). If IssueID 2 has no ticket, it will be on (NULL, 2). Some thought will show that this constraint cannot be duplicated for any row in the table, and still allows multiple NULLs.
You can use the IGNORE
keyword too, example:
update IGNORE table set primary_field = 'value'...............
I just had a similar problem, the DISTINCT keyword works magic:
INSERT INTO Table2(Id, Name) SELECT DISTINCT Id, Name FROM Table1
simply use the Out-File cmd but DON'T forget to give an encoding type:
-Encoding UTF8
so use it so:
$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8
-Append is required if you want to write in the file more then once.
First, what happens when T0 is not None
? I would test that, then I would adjust the values I pass to plt.subplot()
; maybe try values 131, 132, and 133, or values that depend whether or not T0
exists.
Second, after plt.show()
is called, a new figure is created. To deal with this, you can
Call plt.savefig('tessstttyyy.png', dpi=100)
before you call plt.show()
Save the figure before you show()
by calling plt.gcf()
for "get current figure", then you can call savefig()
on this Figure
object at any time.
For example:
fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)
In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.
Most Recent working method:
getColor(R.color.snackBarAction)
I added my pubkey to github.com and this was successful:
ssh -T [email protected]
But I received the "You can't push" error after having wrongly done this:
git clone git://github.com/mygithubacct/dotfiles.git
git remote add origin [email protected]:mygithubacct/dotfiles.git
...edit/add/commit
git push origin master
Instead of doing what I should have done:
mkdir dotfiles
cd dotfiles
git init
git remote add origin [email protected]:mygithubacct/dotfiles.git
git pull origin master
...edit/add/commit
git push origin master
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
I had this problem and all I had to do is return true
from touchend and the warning went away.
Make sure your package.json
is valid...
I had the following error...
npm WARN Invalid name: "blah blah blah"
and that, similarly, caused devDependencies
not to be installed.
FYI, changing the package.json
"name" to blah-blah-blah
fixed it.
I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the ability to select at run-time the most-derived override of a method.
Consider the following code:
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
What is the output of this program?
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
Derived overrides every method of Base: not just the virtual one, but also the non-virtual.
We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base*, that NonVirtual is not virtual, so it does the resolution on class Base.
However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at run-time, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.
I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden.
I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20
The support library android-support-v4.jar
is causing this conflict, just delete the library under /libs
folder of your project, don´t be scared, the library is already contained in the library appcompat_v7
, clean and build your project, and your project will work like a charm!
You could try something like this:
...Binding="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...
From the documentation:
get cookie from response
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies
{'example_cookie_name': 'example_cookie_value'}
give cookie back to server on subsequent request
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)`
Here is a short rundown:
conda build
that builds packages from source, but conda install
itself installs things from already built Conda packages. In both cases:
The first two bullet points of Conda are really what make it advantageous over pip for many packages. Since pip installs from source, it can be painful to install things with it if you are unable to compile the source code (this is especially true on Windows, but it can even be true on Linux if the packages have some difficult C or FORTRAN library dependencies). Conda installs from binary, meaning that someone (e.g., Continuum) has already done the hard work of compiling the package, and so the installation is easy.
There are also some differences if you are interested in building your own packages. For instance, pip is built on top of setuptools, whereas Conda uses its own format, which has some advantages (like being static, and again, Python agnostic).
None of the other answers were working for me immediately on ElementaryOS Freya (based on Ubuntu 14.04); I was getting the
[TerminalIPythonApp] WARNING | File not found: 'kernelspec'
error that quickbug described under Matt's answer. I had to first do:
sudo apt-get install pip3
, then
sudo pip3 install ipython[all]
At that point you can then run the commands that Matt suggested; namely: ipython kernelspec install-self
and ipython3 kernelspec install-self
Now when I launch ipython notebook
and then open a notebook, I am able to select the Python 3 kernel from the Kernel menu.
On almost every system I've met uint8_t == unsigned char, but this is not guaranteed by the C standard. If you are trying to write portable code and it matters exactly what size the memory is, use uint8_t. Otherwise use unsigned char.
This will give you what u are requesting for:
select convert(varchar(3),datename(month, S0.OrderDateTime))
You need to do
./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl
Instead of this
./configure --with-ssl=openssl
$ git rebase --abort
Run this code at any time if you want to undo the git rebase
$ git rebase -i HEAD~2
To reapply last two commits. The above command will open a code editor
After :wq you will be in active rebase mode
Note: You'll get another editor if no warning/error messages, If there is an error or warning another editor will not show, you may abort by runnning
$ git rebase --abort
if you see an error or warning else just continue by running $ git rebase --continue
You will see your 2 commit message. Choose one or write your own commit message, save and quit [:wq]
Note 2: You may need to force push your changes to the remote repo if you run rebase command
$ git push -f
$ git push -f origin master
The relevant Python documentation suggests the use of the EAFP coding style (Easier to Ask for Forgiveness than Permission). This means that the code
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print "\nBE CAREFUL! Directory %s already exists." % path
is better than the alternative
if not os.path.exists(path):
os.makedirs(path)
else:
print "\nBE CAREFUL! Directory %s already exists." % path
The documentation suggests this exactly because of the race condition discussed in this question. In addition, as others mention here, there is a performance advantage in querying once instead of twice the OS. Finally, the argument placed forward, potentially, in favour of the second code in some cases --when the developer knows the environment the application is running-- can only be advocated in the special case that the program has set up a private environment for itself (and other instances of the same program).
Even in that case, this is a bad practice and can lead to long useless debugging. For example, the fact we set the permissions for a directory should not leave us with the impression permissions are set appropriately for our purposes. A parent directory could be mounted with other permissions. In general, a program should always work correctly and the programmer should not expect one specific environment.
.length = number of rows / column length
[0].length = number of columns / row length
Based on the answer I linked to in my comment above, this should work:
delete from
(
select pf.* From PRODUCTFILTERS pf
where pf.id>=200
And pf.rowid in
(
Select rowid from PRODUCTFILTERS
inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID
And PRODUCTS.NAME= 'Mark'
)
);
or
delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf
where pf.id>=200
And pf.rowid in
(
Select PRODUCTFILTERS.rowid from PRODUCTFILTERS
inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID
And PRODUCTS.NAME= 'Mark'
)
);
I see a lot of these answers rely on reading the whole text file into memory instead of taking it one chunk at a time. Here's my solution in nice modern Swift, using FileHandle to keep memory impact low:
enum MyError {
case invalidTextFormat
}
extension FileHandle {
func readLine(maxLength: Int) throws -> String {
// Read in a string of up to the maximum length
let offset = offsetInFile
let data = readData(ofLength: maxLength)
guard let string = String(data: data, encoding: .utf8) else {
throw MyError.invalidTextFormat
}
// Check for carriage returns; if none, this is the whole string
let substring: String
if let subindex = string.firstIndex(of: "\n") {
substring = String(string[string.startIndex ... subindex])
} else {
substring = string
}
// Wind back to the correct offset so that we don't miss any lines
guard let dataCount = substring.data(using: .utf8, allowLossyConversion: false)?.count else {
throw MyError.invalidTextFormat
}
try seek(toOffset: offset + UInt64(dataCount))
return substring
}
}
Note that this preserves the carriage return at the end of the line, so depending on your needs you may want to adjust the code to remove it.
Usage: simply open a file handle to your target text file and call readLine
with a suitable maximum length - 1024 is standard for plain text, but I left it open in case you know it will be shorter. Note that the command will not overflow the end of the file, so you may have to check manually that you've not reached it if you intend to parse the entire thing. Here's some sample code that shows how to open a file at myFileURL
and read it line-by-line until the end.
do {
let handle = try FileHandle(forReadingFrom: myFileURL)
try handle.seekToEndOfFile()
let eof = handle.offsetInFile
try handle.seek(toFileOffset: 0)
while handle.offsetInFile < eof {
let line = try handle.readLine(maxLength: 1024)
// Do something with the string here
}
try handle.close()
catch let error {
print("Error reading file: \(error.localizedDescription)"
}
The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:
file sum___19.0, per Iteration___19.0 raf sum___16.0, per Iteration___16.0 channel sum__273.0, per Iteration__273.0
For 100 runs and 10000 iterations I get:
file sum__1767629.0, per Iteration__1.7676290000000001 raf sum___881284.0, per Iteration__0.8812840000000001 channel sum___414286.0, per Iteration__0.414286
I did run the following modified code giving as an argument the name of a 100MB file.
import java.io.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
public class FileSizeBench {
private static File file;
private static FileChannel channel;
private static RandomAccessFile raf;
public static void main(String[] args) throws Exception {
int runs = 1;
int iterations = 1;
file = new File(args[0]);
channel = new FileInputStream(args[0]).getChannel();
raf = new RandomAccessFile(args[0], "r");
HashMap<String, Double> times = new HashMap<String, Double>();
times.put("file", 0.0);
times.put("channel", 0.0);
times.put("raf", 0.0);
long start;
for (int i = 0; i < runs; ++i) {
long l = file.length();
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != file.length()) throw new Exception();
times.put("file", times.get("file") + System.nanoTime() - start);
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != channel.size()) throw new Exception();
times.put("channel", times.get("channel") + System.nanoTime() - start);
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != raf.length()) throw new Exception();
times.put("raf", times.get("raf") + System.nanoTime() - start);
}
for (Map.Entry<String, Double> entry : times.entrySet()) {
System.out.println(
entry.getKey() + " sum: " + 1e-3 * entry.getValue() +
", per Iteration: " + (1e-3 * entry.getValue() / runs / iterations));
}
}
}
Centos 7 php install comes with the ModSecurity package installed and enabled which prevents web access to phpMyAdmin. At the end of phpMyAdmin.conf, you should find
# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc. This may break your mod_security implementation.
#
#<IfModule mod_security.c>
# <Directory /usr/share/phpMyAdmin/>
# SecRuleInheritance Off
# </Directory>
#</IfModule>
which gives you the answer to the problem. By adding
SecRuleEngine Off
in the block "Directory /usr/share/phpMyAdmin/", you can solve the 'denied access' to phpmyadmin, but you may create security issues.
It is possible to center a video inside an element just like a cover
sized background-image
without JS using the object-fit
attribute or CSS Transforms
.
As pointed in the comments, it is possible to achieve the same result without CSS transform
, but using object-fit
, which I think it's an even better option for the same result:
.video-container {
height: 300px;
width: 300px;
position: relative;
}
.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
You can set a video as a background to any HTML element easily thanks to transform
CSS property.
Note that you can use the transform
technique to center vertically and horizontally any HTML element.
.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}
.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
I couldn't get your method to work @Damien-at-SF...
So I resorted to my old knowledge.
By encasing the input type="button" within a hyperlink element, you can simply declare the target property as so:
<a href="http://www.site.org" target="_blank">
<input type="button" class="button" value="Open" />
</a>
The 'target="_blank"' is the property which makes the browser open the link within a new tab. This attribute has other properties, See: http://www.w3schools.com/tags/att_a_target.asp for further details.
Since the 'value=""' attribute on buttons will write the contained string to the button, a span is not necessary.
Instead of writing:
<element></element>
for most HTML elements you can simply close them with a trailing slash, like so:
<element />
Oh, and finally... a 'button' element has a refresh trigger within it, so I use an 'input type[button]' to avoid triggering the form.
Good Luck Programmers.
Due to StackOverflow's policy I had to change the domain in the example: https://meta.stackexchange.com/questions/208963/why-are-certain-example-urls-like-http-site-com-and-http-mysite-com-blocke
This functionality has been added to the IDE now (working Pycharm 2018.3)
Just click the EnvFile
tab in the run configuration, click Enable EnvFile
and click the + icon to add an env file
Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.
No, You cannot publish on Github pages. Try Heroku or something like that. You can only deploy static sites on github pages. You can't deploy a server on github pages.
\040
matches exactly the space character.
New Link
Escape sequences for Regex PHP
Try this one..
// Browser with version Detection
navigator.sayswho= (function(){
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
})();
var browser_version = navigator.sayswho;
alert("Welcome to " + browser_version);
check out the working fiddle ( here )
I know this was posted about a year ago, but this is for users for future reference.
I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.
while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.
if (email == null)
{
break;
}
else
{
// your code here
}
Simply,
$res = (object)array("success"=>false); // $res->success = bool(false);
Or you could instantiate classes with:
$res = (object)array(); // object(stdClass) -> recommended
$res = (object)[]; // object(stdClass) -> works too
$res = new \stdClass(); // object(stdClass) -> old method
and fill values with:
$res->success = !!0; // bool(false)
$res->success = false; // bool(false)
$res->success = (bool)0; // bool(false)
More infos: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting
THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.
You need to right click on Windows authentication and choose providers menu item.
Hope this helps to save some time.
If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTests
or any other class that extends AbstractSpringContextTests
), you can access the app context by calling the getContext()
method.
Check out the javadocs for the package org.springframework.test.
TL;DR ...and late to the party, but that short explanation might help future googlers..
In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.
A minimal example:
df <- data.frame(a = 1:2); df$a <- 1:3
throws the error
Error in
$<-.data.frame
(*tmp*
, a, value = 1:3) : replacement has 3 rows, data has 2
which is clear, because the vector a
of df
has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).
As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper()
(which implies drug is a string).
But that's not your error, as your function medications_minimum3()
doesn't even use the second argument (something you should fix).
TypeError: unhashable type: 'list'
usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1
-- are you sure that row[11]
is of the right type? Sounds to me it might be a list.
Here is another way
timestamps.sort()
timestamps.reverse()
print(timestamps)
let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
let arr = Object.values(obj);
let min = Math.min(...arr);
let max = Math.max(...arr);
console.log( `Min value: ${min}, max value: ${max}` );
_x000D_
Try this:
let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var arr = Object.keys( obj ).map(function ( key ) { return obj[key]; });
and then:
var min = Math.min.apply( null, arr );
var max = Math.max.apply( null, arr );
Live demo: http://jsfiddle.net/7GCu7/1/
If you are Windows guy and using "Tortoise SVN' user.
Select the File. Right Click. Option 'Tortoise SVN' --> get Lock. Use option 'Steal The Lock'.
Yes. If you have your list of packages, compare it to the output from installed.packages()[,"Package"]
and install the missing packages. Something like this:
list.of.packages <- c("ggplot2", "Rcpp")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
Otherwise:
If you put your code in a package and make them dependencies, then they will automatically be installed when you install your package.
Almost done. Quoting from http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip
The chars argument is a string specifying the set of characters to be removed.
[...]
The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
So the argument is not a regexp.
>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>>
Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!
Polymorphism is the ability to treat a class of object as if it is the parent class.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;
try this for hide
$('#table_id').DataTable({
"info": false
});
and try this for change label
$('#table_id').DataTable({
"oLanguage": {
"sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
},
});
SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update
UPDATE table
SET col1 = NULL
WHERE col1 = ''
NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.
If you want to do it during your copy from one table to another, use this:
INSERT INTO newtable ( col1, othercolumn )
SELECT
NULLIF(col1, ''),
othercolumn
FROM table
const data = [{"b":1,"c":100},{"a":1,"b":1,"c":150},{"a":1,"b":2,"c":100},{"a":2,"b":1,"c":13}]
const result = data.reduce((r, e) => {
r['a'] += (e['a'] ? e['a'] : 0)
r['d'] += (e['b'] ? e['b'] : 0)
r['c'] += (e['c'] ? e['c'] : 0)
return r
}, {'a':0, 'd':0, 'c':0})
console.log(result)
`result` { a: 4, d: 5, c: 363 }
When you are using curl
sometimes give you 403 (access forbidden)
Solved by adding this line to emulate browser.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Hope this help someone.
Step 1 :
Create ts : app/_helpers/must-match.validator.ts
import { FormGroup } from '@angular/forms';
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
Step 2 :
Use in your component.ts
import { MustMatch } from '../_helpers/must-match.validator';
ngOnInit() {
this.loginForm = this.formbuilder.group({
Password: ['', [Validators.required, Validators.minLength(6)]],
ConfirmPassword: ['', [Validators.required]],
}, {
validator: MustMatch('Password', 'ConfirmPassword')
});
}
Step 3 :
Use In View/Html
<input type="password" formControlName="Password" class="form-control" autofocus>
<div *ngIf="loginForm.controls['Password'].invalid && (loginForm.controls['Password'].dirty || loginForm.controls['Password'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['Password'].errors.required">Password Required. </div>
<div *ngIf="loginForm.controls['Password'].errors.minlength">Password must be at least 6 characters</div>
</div>
<input type="password" formControlName="ConfirmPassword" class="form-control" >
<div *ngIf="loginForm.controls['ConfirmPassword'].invalid && (loginForm.controls['ConfirmPassword'].dirty || loginForm.controls['ConfirmPassword'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.required">ConfirmPassword Required. </div>
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.mustMatch">Your password and confirmation password do not match.</div>
</div>
OpenSSL provides a passwd command that can encrypt but doesn't decrypt as it only does hashes. You could also download something like aesutil so you can use a capable and well-known symmetric encryption routine.
For example:
#!/bin/sh
# using aesutil
SALT=$(mkrand 15) # mkrand generates a 15-character random passwd
MYENCPASS="i/b9pkcpQAPy7BzH2JlqHVoJc2mNTBM=" # echo "passwd" | aes -e -b -B -p $SALT
MYPASS=$(echo "$MYENCPASS" | aes -d -b -p $SALT)
# and usage
serverControl.sh -u admin -p $MYPASS -c shutdown
It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.
The best design would be to have the labels on a constant background with the images changing behind that.
You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.
To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.
The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.
Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.
Taking it further you could even parse on the fly
e.g.
& "my.exe" | %{
if ($_ -match 'OK')
{ Write-Host $_ -f Green }
else if ($_ -match 'FAIL|ERROR')
{ Write-Host $_ -f Red }
else
{ Write-Host $_ }
}
What about this one :
<DockPanel Margin="8">
<Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
<TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</Border>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>
The following complete example will read an existing server.xml
file from the current directory, append a new Server and re-write the file to server.xml
. It does not work without an existing .xml file, so you will need to modify the code to handle that case.
import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class AddXmlNode {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("server.xml");
Element root = document.getDocumentElement();
Collection<Server> servers = new ArrayList<Server>();
servers.add(new Server());
for (Server server : servers) {
// server elements
Element newServer = document.createElement("server");
Element name = document.createElement("name");
name.appendChild(document.createTextNode(server.getName()));
newServer.appendChild(name);
Element port = document.createElement("port");
port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
newServer.appendChild(port);
root.appendChild(newServer);
}
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult("server.xml");
transformer.transform(source, result);
}
public static class Server {
public String getName() { return "foo"; }
public Integer getPort() { return 12345; }
}
}
Example server.xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
<server>
<name>something</name>
<port>port</port>
</server>
</Servers>
The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml
and then just appends a new Server element and re-writes the file.
You are not initializing connection.That's why this kind of error is coming to you.
Your code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
Corrected code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);
In vue cli-3 You can define the variable in main.js like
window.basurl="http://localhost:8000/";
And you can also access this variable in any component by using the the window.basurl
Use some regex like [0-9]
or \d
:
$words = preg_replace('/\d+/', '', $words );
You might want to read the preg_replace() documentation as this is directly shown there.
In case you want send your custom headers, you can do it this way:
curl -v -H @{'custom_header'='custom_header_value'} http://localhost:3000/action?result1=gh&result2=ghk
Through Programming:
btn.setBackgroundColor(getResources().getColor(R.color.colorOffWhite));
and your colors.xml must contain...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorOffWhite">#80ffffff</color>
</resources>
select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
from table1
where IsCurrent = 1
Simple Example:
func method(arg: Bool, completion: (Bool) -> ()) {
print("First line of code executed")
// do stuff here to determine what you want to "send back".
// we are just sending the Boolean value that was sent in "back"
completion(arg)
}
How to use it:
method(arg: true, completion: { (success) -> Void in
print("Second line of code executed")
if success { // this will be equal to whatever value is set in this method call
print("true")
} else {
print("false")
}
})
To add a WHERE clause inside an INSERT statement simply;
INSERT INTO table_name (column1,column2,column3)
SELECT column1, column2, column3 FROM table_name
WHERE column1 = 'some_value'
This takes the last. Not the maximum though:
In [10]: df.drop_duplicates(subset='A', keep="last")
Out[10]:
A B
1 1 20
3 2 40
4 3 10
You can do also something like:
In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]:
A B
A
1 1 20
2 2 40
3 3 10
An int64_t should be 64 bits wide on any platform (hence the name), whereas a long can have different lengths on different platforms. In particular, sizeof(long) is often 4, ie. 32 bits.
Use assertNotNull(obj)
. assert
means must be
.
Like already said, the -cp is just for telling the jvm in the command line which class to use for the main thread and where it can find the libraries (define classpath). In -jar it expects the class-path and main-class to be defined in the jar file manifest. So other is for defining things in command line while other finding them inside the jar manifest. There is no difference in performance. You can't use them at the same time, -jar will override the -cp.
Though even if you use -cp, it will still check the manifest file. So you can define some of the class-paths in the manifest and some in the command line. This is particularly useful when you have a dependency on some 3rd party jar, which you might not provide with your build or don't want to provide (expecting it to be found already in the system where it's to be installed for example). So you can use it to provide external jars. It's location may vary between systems or it may even have a different version on different system (but having the same interfaces). This way you can build the app with other version and add the actual 3rd party dependency to class-path on the command line when running it on different systems.
From the Android Developers page,
onPause():
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
onStop():
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.
The paused Activity gets a Resume and Stopped gets Restarted.
When you call this.finish()
, onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.
I hope it's clear enough.
After calling GroupBy
, you get a series of groups IEnumerable<Grouping>
, where each Grouping itself exposes the Key
used to create the group and also is an IEnumerable<T>
of whatever items are in your original data set. You just have to call Count()
on that Grouping to get the subtotal.
foreach(var line in data.GroupBy(info => info.metric)
.Select(group => new {
Metric = group.Key,
Count = group.Count()
})
.OrderBy(x => x.Metric))
{
Console.WriteLine("{0} {1}", line.Metric, line.Count);
}
I'm assuming you already have a list/array of some class
that looks like
class UserInfo {
string name;
int metric;
..etc..
}
...
List<UserInfo> data = ..... ;
When you do data.GroupBy(x => x.metric)
, it means "for each element x
in the IEnumerable defined by data
, calculate it's .metric
, then group all the elements with the same metric into a Grouping
and return an IEnumerable
of all the resulting groups. Given your example data set of
<DATA> | Grouping Key (x=>x.metric) |
joe 1 01/01/2011 5 | 1
jane 0 01/02/2011 9 | 0
john 2 01/03/2011 0 | 2
jim 3 01/04/2011 1 | 3
jean 1 01/05/2011 3 | 1
jill 2 01/06/2011 5 | 2
jeb 0 01/07/2011 3 | 0
jenn 0 01/08/2011 7 | 0
it would result in the following result after the groupby:
(Group 1): [joe 1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb 0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim 3 01/04/2011 1]
The original question was how to rename a tag, which is easy: first create NEW as an alias of OLD: git tag NEW OLD
then delete OLD: git tag -d OLD
.
The quote regarding "the Git way" and (in)sanity is off base, because it's talking about preserving a tag name, but making it refer to a different repository state.
I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.
You can use islower()
on your string to see if it contains some lowercase letters (amongst other characters). or
it with isupper()
to also check if contains some uppercase letters:
below: letters in the string: test yields true
>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True
below: no letters in the string: test yields false.
>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>>
Not to be mixed up with isalpha()
which returns True
only if all characters are letters, which isn't what you want.
Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.
The following css statement disables click events
pointer-events:none;
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
This is a fair few years later, but the Facebook Graph API Explorer now has a little info symbol next to the access token that allows you to access the access token tool app, and extend the API token for a couple of months. Might be helpful during development.
You can also do it without modulus. Just reset your counter when it matches.
if($counter == 2) { // matches every 3 iterations
echo 'image-file';
$counter = 0;
}
var obj = {...};
for (var key in obj) {
var value = obj[key];
}
The php syntax is just sugar.
After some great help from steinar this is what worked for me:
public void ExecuteCommand(string command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process process;
ProcessInfo = new ProcessStartInfo(Application.StartupPath + "\\txtmanipulator\\txtmanipulator.bat", command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
ProcessInfo.WorkingDirectory = Application.StartupPath + "\\txtmanipulator";
// *** Redirect the output ***
ProcessInfo.RedirectStandardError = true;
ProcessInfo.RedirectStandardOutput = true;
process = Process.Start(ProcessInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
ExitCode = process.ExitCode;
MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
process.Close();
}
Label myLabel = new Label ();
myLabel.Content = "Hello World!";
Quoting Chris: "... when your program quits, any daemon threads are killed automatically.". I think that sums it up. You should be careful when you use them as they abruptly terminate when main program executes to completion.
Configuration all files with postgres 12 on centos:
step 1: search and edit file
sudo vi /var/lib/pgsql/12/data/pg_hba.conf
press "i" and at line IPv4 change
host all all 0.0.0.0/0 md5
step 2: search and edit file postgresql.conf
sudo vi /var/lib/pgsql/12/data/postgresql.conf
add last line: listen_addresses = '*' :wq! (save file) - step 3: restart
systemctl restart postgresql-12.service
Dim regDate As Date = Date.Now.date
This should fix your problem, though it's 2 years old!
There is actually a comparison of the two in the official WebStorm FAQ. However, the version history of that page shows it was last updated December 13, so I'm not sure if it's maintained.
This is an extract from the FAQs for reference:
What is WebStorm & PhpStorm?
WebStorm & PhpStorm are IDEs (Integrated Development Environment) built on top of JetBrains IntelliJ platform and narrowed for web development.
Which IDE do I need?
PhpStorm is designed to cover all needs of PHP developer including full JavaScript, CSS and HTML support. WebStorm is for hardcore JavaScript developers. It includes features PHP developer normally doesn’t need like Node.JS or JSUnit. However corresponding plugins can be installed into PhpStorm for free.
How often new vesions (sic) are going to be released?
Preliminarily, WebStorm and PhpStorm major updates will be available twice in a year. Minor (bugfix) updates are issued periodically as required.
snip
IntelliJ IDEA vs WebStorm features
IntelliJ IDEA remains JetBrains' flagship product and IntelliJ IDEA provides full JavaScript support along with all other features of WebStorm via bundled or downloadable plugins. The only thing missing is the simplified project setup.
I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.
It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.
I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell.
rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:
dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))
or
dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))
The worksheet function sum will correctly ignore blank spaces.
Let me know if this helps!
Based on this fantastic post
http://code.activestate.com/recipes/217212-treepy-graphically-displays-the-directory-structur/
Here es a refinement to behave exactly like
http://linux.die.net/man/1/tree
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # tree.py # # Written by Doug Dahms # # Prints the tree structure for the path specified on the command line from os import listdir, sep from os.path import abspath, basename, isdir from sys import argv def tree(dir, padding, print_files=False, isLast=False, isFirst=False): if isFirst: print padding.decode('utf8')[:-1].encode('utf8') + dir else: if isLast: print padding.decode('utf8')[:-1].encode('utf8') + '+-- ' + basename(abspath(dir)) else: print padding.decode('utf8')[:-1].encode('utf8') + '+-- ' + basename(abspath(dir)) files = [] if print_files: files = listdir(dir) else: files = [x for x in listdir(dir) if isdir(dir + sep + x)] if not isFirst: padding = padding + ' ' files = sorted(files, key=lambda s: s.lower()) count = 0 last = len(files) - 1 for i, file in enumerate(files): count += 1 path = dir + sep + file isLast = i == last if isdir(path): if count == len(files): if isFirst: tree(path, padding, print_files, isLast, False) else: tree(path, padding + ' ', print_files, isLast, False) else: tree(path, padding + '¦', print_files, isLast, False) else: if isLast: print padding + '+-- ' + file else: print padding + '+-- ' + file def usage(): return '''Usage: %s [-f] Print tree structure of path specified. Options: -f Print files as well as directories PATH Path to process''' % basename(argv[0]) def main(): if len(argv) == 1: print usage() elif len(argv) == 2: # print just directories path = argv[1] if isdir(path): tree(path, '', False, False, True) else: print 'ERROR: \'' + path + '\' is not a directory' elif len(argv) == 3 and argv[1] == '-f': # print directories and files path = argv[2] if isdir(path): tree(path, '', True, False, True) else: print 'ERROR: \'' + path + '\' is not a directory' else: print usage() if __name__ == '__main__': main()
another approach is to use the double colons:
mtcars %>%
dplyr::group_by(cyl, gear) %>%
dplyr::summarise(length(gear))
If you have deleted multiple files locally but not committed, you can force checkout
$ git checkout -f HEAD
Try the Magnific Popup, it's responsive and weights just around 3KB.
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:
Test connection:
Same thing for tooltips:
For me following solution works because it does not add event listeners on every 'mouseenter' and it is possible to hover back on the tooltip element which keeps the tooltip alive.
$ ->
$('.element').tooltip({
html: true,
trigger: 'manual'
}).
on 'mouseenter', ->
clearTimeout window.tooltipTimeout
$(this).tooltip('show') unless $('.tooltip:visible').length > 0
.
on 'mouseleave', ->
_this = this
window.tooltipTimeout = setTimeout ->
$(_this).tooltip('hide')
, 100
$(document).on 'mouseenter', '.tooltip', ->
clearTimeout window.tooltipTimeout
$(document).on 'mouseleave', '.tooltip', ->
trigger = $($(this).siblings('.element')[0])
window.tooltipTimeout = setTimeout ->
trigger.tooltip('hide')
, 100
In Python 3, print is a function, you need to call it like print("hello world")
.
Just adding this for multiple filters attaching to Q
object, if someone might be looking to it.
If a Q
object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.
an example would be
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')
Here the OR condition and a filter with category of income is taken into account
I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.
It's not part of PHP; it's part of Apache.
http://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files provide a way to make configuration changes on a per-directory basis.
Essentially, it allows you to take directives that would normally be put in Apache's main configuration files, and put them in a directory-specific configuration file instead. They're mostly used in cases where you don't have access to the main configuration files (e.g. a shared host).
I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following https://github.com/shakalaca/MagiskOnEmulator
Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk.
You can't use fetch in actions without middleware. Actions must be plain objects. You can use a middleware like redux-thunk or redux-saga to do fetch and then dispatch another action.
Here is an example of async action using redux-thunk middleware.
export function checkUserLoggedIn (authCode) {
let url = `${loginUrl}validate?auth_code=${authCode}`;
return dispatch => {
return fetch(url,{
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}
)
.then((resp) => {
let json = resp.json();
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})
.then(
json => {
if (json.result && (json.result.status === 'error')) {
dispatch(errorOccurred(json.result));
dispatch(logOut());
}
else{
dispatch(verified(json.result));
}
}
)
.catch((error) => {
dispatch(warningOccurred(error, url));
})
}
}
<properties>
<!-- Use the latest version whenever possible. -->
<jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
you have a ObjectMapper (from Jackson Databind package) handy. if so, you can do:
JsonFactory factory = objectMapper.getFactory();
Source: https://github.com/FasterXML/jackson-core
So, the 3 "fasterxml" dependencies which you already have in u'r pom are enough for ObjectMapper as it includes jackson-databind.
The error is self-explanatory... doInBackground()
runs on a background thread which, since it is not intended to loop, is not connected to a Looper
.
You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground()
implementation returns will be passed to onPostExecute()
which runs on the UI thread.
mActivity = ThisActivity.this;
mActivity.runOnUiThread(new Runnable() {
public void run() {
new asyncCreateText().execute();
}
});
ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:
Looks like you're trying to start an AsyncTask
from a GL rendering thread... don't do that cos they won't ever Looper.loop()
either. AsyncTasks are really designed to be run from the UI thread only.
The least disruptive fix would probably be to call Activity.runOnUiThread()
with a Runnable
that kicks off your AsyncTask
.
To make it do nothing at all, use this:
<a href="javascript:void(0)"> ... </a>
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
It's now supported with pseudo elements in each of WebKit, Firefox and IE. But, of course, it's different in each one. : (
See this question's answers and/or search for a CodePen titled prettify <input type=range> #101
for some solutions.
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
long l = reinterpret_cast<long>(i)
static_cast
is the one which has to be used here. See this and this SO questions.
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
Just append a div
with that class to body
, then remove it when you're done:
// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);
// Remove it (later)
$(".modal-backdrop").remove();
Live Example:
$("input").click(function() {_x000D_
var bd = $('<div class="modal-backdrop"></div>');_x000D_
bd.appendTo(document.body);_x000D_
setTimeout(function() {_x000D_
bd.remove();_x000D_
}, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
Try it ;) Just watch the content of the FrameLayout(@id/tabcontent), because I don't know how it will handle in case of scrolling... In my case it works because I used ListView as the content of my tabs. :) Hope it helps.
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_above="@android:id/tabs" />
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</TabHost>
container can not come front to inner container. but try this below :
Css :
----------------------
.container { position:relative; }
.div1 { width:100px; height:100px; background:#9C3; position:absolute;
z-index:1000; left:50px; top:50px; }
.div2 { width:200px; height:200px; background:#900; }
HTMl :
-----------------------
<div class="container">
<div class="div1">
Div1 content here .........
</div>
<div class="div2">
Div2 contenet here .........
</div>
</div>
Here is my solution. The code should be easy enough to follow but here is the idea:
The code:
function focusFirst(parent) {
$(parent).find('input, textarea, select')
.not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
.filter(':enabled:visible:first')
.focus();
}
Then simply call focusFirst with your parent element or selector.
Selector:
focusFirst('form#aspnetForm');
Element:
var el = $('form#aspnetForm');
focusFirst(el);
It is technically possible to put a caption on an ImageButton
if you really want to do it. Just put a TextView
over the ImageButton
using FrameLayout
. Just remember to not make the Textview
clickable.
Example:
<FrameLayout>
<ImageButton
android:id="@+id/button_x"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@null"
android:scaleType="fitXY"
android:src="@drawable/button_graphic" >
</ImageButton>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:text="TEST TEST" >
</TextView>
</FrameLayout>
I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.
It can use for use to read for Zeor base index or 1 one base index.
${loop.count}` it will give 1 starting base index.
${loop.index} it will give 0 base index as normal Index of array
start from 0.
For Example :
<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
<source srcset="${currentImage}" media="(min-width: 1000px)"></source>
<source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
<img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>
For more Info please refer this link
$broadcast
or $emit
.nobody mentioned this
$(function() {
// place your code
});
which is a shorthand function of
$(document).ready(function() { .. });
Try this awk
awk -F, '{$0=$3}1' file
column3
,
Divide fields by ,
$0=$3
Set the line to only field 3
1
Print all out. (explained here)This could also be used:
awk -F, '{print $3}' file
GitHub now has an import option that lets you choose whatever you want your new imported repository public or private
As reported by Tim Anderson
Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.
Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.
Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.
Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.
edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)
Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:
We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)
This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.
Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.
The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.
To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.
PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.
Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.
Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.
Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).
Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.
The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.
So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.
Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO
Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.
In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.
From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.
In my opinion there are several HUGE advantages including
Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.
My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.
I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.
You entered an alphanumeric and int, blank delimited in mystr
.
You then tried to convert the first token (blank delimited) into an int
.
The first token was RS which failed to convert to int
, leaving a zero for myprice, and we all know what zero times anything yields.
When you only entered int values the second time, everything worked as you expected.
It was the spurious RS that caused your code to fail.
As mentioned array.find()
is not supported in IE.
However you can read about a Polyfill here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill
This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet:
Code:
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}
This may not solve all of your problems, but the variable you are using inside your function (text) is not the same as the parameter you are passing in (x).
Changing:
function textreplace(x) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
To:
function textreplace(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
seems like it would do some good.
Redefine the console.log function in your script.
console.log = function() {}
That's it, no more messages to console.
EDIT:
Expanding on Cide's idea. A custom logger which you can use to toggle logging on/off from your code.
From my Firefox console:
var logger = function()
{
var oldConsoleLog = null;
var pub = {};
pub.enableLogger = function enableLogger()
{
if(oldConsoleLog == null)
return;
window['console']['log'] = oldConsoleLog;
};
pub.disableLogger = function disableLogger()
{
oldConsoleLog = console.log;
window['console']['log'] = function() {};
};
return pub;
}();
$(document).ready(
function()
{
console.log('hello');
logger.disableLogger();
console.log('hi', 'hiya');
console.log('this wont show up in console');
logger.enableLogger();
console.log('This will show up!');
}
);
How to use the above 'logger'? In your ready event, call logger.disableLogger so that console messages are not logged. Add calls to logger.enableLogger and logger.disableLogger inside the method for which you want to log messages to the console.
I used iTextsharp with c# to combine pdf files. This is the code I used.
string[] lstFiles=new string[3];
lstFiles[0]=@"C:/pdf/1.pdf";
lstFiles[1]=@"C:/pdf/2.pdf";
lstFiles[2]=@"C:/pdf/3.pdf";
PdfReader reader = null;
Document sourceDocument = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage;
string outputPdfPath=@"C:/pdf/new.pdf";
sourceDocument = new Document();
pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
//Open the output file
sourceDocument.Open();
try
{
//Loop through the files list
for (int f = 0; f < lstFiles.Length-1; f++)
{
int pages =get_pageCcount(lstFiles[f]);
reader = new PdfReader(lstFiles[f]);
//Add pages of current file
for (int i = 1; i <= pages; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
reader.Close();
}
//At the end save the output file
sourceDocument.Close();
}
catch (Exception ex)
{
throw ex;
}
private int get_pageCcount(string file)
{
using (StreamReader sr = new StreamReader(File.OpenRead(file)))
{
Regex regex = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/
There is a search order for assemblies when building. The search order is as follows:
So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.
SSH File
~/.ssh/config file
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
LogLevel QUIET
ConnectTimeout=10
Host github.com
User git
AddKeystoAgent yes
UseKeychain yes
Identityfile ~/github_rsa
Edit reponame/.git/config
[remote "origin"]
url = [email protected]:username/repo.git
Try the following:
grep -v -e '^$' foo.txt
The -e
option allows regex patterns for matching.
The single quotes around ^$
makes it work for Cshell. Other shells will be happy with either single or double quotes.
UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with "\r\n" style line endings), whereas the above only removes files with blank lines and unix style line endings:
grep -v -e '^[[:space:]]*$' foo.txt
What even is ‘children’?
The React docs say that you can use
props.children
on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.My simple explanation of what
this.props.children
does is that it is used to display whatever you include between the opening and closing tags when invoking a component.A simple example:
Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no
this
keyword so just useprops.children
const Picture = (props) => {
return (
<div>
<img src={props.src}/>
{props.children}
</div>
)
}
This component contains an
<img>
that is receiving someprops
and then it is displaying{props.children}
.Whenever this component is invoked
{props.children}
will also be displayed and this is just a reference to what is between the opening and closing tags of the component.
//App.js
render () {
return (
<div className='container'>
<Picture key={picture.id} src={picture.src}>
//what is placed here is passed as props.children
</Picture>
</div>
)
}
Instead of invoking the component with a self-closing tag
<Picture />
if you invoke it will full opening and closing tags<Picture> </Picture>
you can then place more code between it.This de-couples the
<Picture>
component from its content and makes it more reusable.
Reference: A quick intro to React’s props.children
I use a variation on JOP's answer. Using command line parameters you can set the debugging mode in the IDE with project properties or through the Windows service manager.
protected override void OnStart(string[] args)
{
if (args.Contains<string>("DEBUG_SERVICE"))
{
Debugger.Break();
}
...
}
Built a tiny, confirm-like vanilla js yes / no dialog.
https://www.npmjs.com/package/yesno-dialog