Ensure that binary files are under "bin" subdirectory of your ".svc" file
Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.
Check this : Using Large Message Requests in Silverlight with WCF
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="TestLargeWCF.Web.MyServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="customBinding0">
<binaryMessageEncoding />
<!-- Start change -->
<httpTransport maxReceivedMessageSize="2097152"
maxBufferSize="2097152"
maxBufferPoolSize="2097152"/>
<!-- Stop change -->
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
<endpoint address=""
binding="customBinding"
bindingConfiguration="customBinding0"
contract="TestLargeWCF.Web.MyService"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport
tag:
<binding name="MyServiceBinding">
<security defaultAlgorithmSuite="Basic256Rsa15"
authenticationMode="MutualCertificate" requireDerivedKeys="true"
securityHeaderLayout="Lax" includeTimestamp="true"
messageProtectionOrder="SignBeforeEncrypt"
messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSignatureConfirmation="false">
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
<secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="4096"
maxNameTableCharCount="16384"/>
</textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
requireClientCertificate="false" />
</binding>
I solved the issue by adding https binding in my IIS websites and adding 443 SSL port and selecting a self signed certificate in binding.
I have tried several solutions mentioned over web, unfortunately without any success. In my project, I have two interfaces(xml/json) for each service. Adding mex endpoints or binding configurations did not helped at all. But, I have noticed, I get this error only when running project with *.svc.cs or *.config file focused. When I run project with IService.cs file focused (where interfaces are defined), service is added without any errors. This is really strange and in my opinion conclusion is bug in Visual Studio 2013. I reproduced same behaviour on several machines(even on Windows Server machine). Hope this helps someone.
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
There are times that I want to include my web service source codes along with its client-side project. Both of them have a separate git repositories. I am actually used to add all files using the command:
git add -A
But for some reason, it only adds the folder. Later on I found out that the server files also have its .git
folder in it so the command doesn't work.
tl;dr: Make sure there are no .git
folder inside the folder you want to stage.
The dialog needs to be started only after the window states of the Activity are initialized This happens only after onresume.
So call
runOnUIthread(new Runnable(){
showInfoMessageDialog("Please check your network connection","Network Alert");
});
in your OnResume function. Do not create dialogs in OnCreate
Edit:
use this
Handler h = new Handler();
h.postDelayed(new Runnable(){
showInfoMessageDialog("Please check your network connection","Network Alert");
},500);
in your Onresume instead of showonuithread
The easiest way is probably with VLOOKUP()
. This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.
For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:
=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)
Then simply fill this formula down the rest of column D.
Explanation:
$D2
specifies the value to search for.Sheet2!$A$2:$B$65535
specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535
). Note I am assuming you have a header cell in row 1.2
specifies a 1-based index of the column to return from within the searched range. The value of 2
will return the second column in the range Sheet2!$A$2:$B$65535
, namely the value of the B
column.FALSE
says to only return exact matches.The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
https://github.com/alexanderdickson/waitForImages
$('selector').waitForImages({
finished: function() {
// ...
},
each: function() {
// ...
},
waitForAll: true
});
You should be using @RequestParam
instead of @ModelAttribute
, e.g.
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
@RequestParam String someAttr) {
}
You can even omit @RequestParam
altogether if you choose, and Spring will assume that's what it is:
@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id,
String someAttr) {
}
Use directly
$paymentDate = strtotime(date("d-m-Y"));
$contractDateBegin = strtotime("01-01-2001");
$contractDateEnd = strtotime("01-01-2015");
Then comparison will be ok cause your 01-01-2015 is valid for PHP's 32bit date-range, stated in strtotime's manual.
For python 2.7 another trick is:
arr = [1,2,3]
for num in arr:
print num,
# will print 1 2 3
Here is the solution I'm using:
const result = `${ window.location.protocol }//${ window.location.host }`;
EDIT:
To add cross-browser compatibility, use the following:
const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;
The best way is to use layers insted of views:
AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; //
AVPlayerLayer *layer = [AVPlayerLayer layer];
[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.view.layer addSublayer:layer];
[player play];
Don't forget to add frameworks:
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
Try this
val intent = Intent(this, Page2::class.java)
startActivity(intent)
Demo
$( '.expand' ).click(function() {_x000D_
$( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
margin-left:auto;_x000D_
margin-right:auto;_x000D_
width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
height:20px;_x000D_
background-color:#CCC;_x000D_
display:block;_x000D_
border:#333 solid 1px;_x000D_
margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
float:right;_x000D_
height: 100%;_x000D_
padding-right:5px;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
width: 100%;_x000D_
height:100px; _x000D_
background-color:#0F3;_x000D_
margin-top: -2px;_x000D_
display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
http://api.jquery.com/toggle/
"Display or hide the matched elements."
This is much shorter in code than using show() and hide() methods.
The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.
I use the following code to create PDF
protected void CreatePDF(Stream stream)
{
using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
{
var writer = PdfWriter.GetInstance(document, stream);
writer.PageEvent = new ITextEvents();
document.Open();
// instantiate custom tag processor and add to `HtmlPipelineContext`.
var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
tagProcessorFactory.AddProcessor(
new TableProcessor(),
new string[] { HTML.Tag.TABLE }
);
//Register Fonts.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
htmlPipelineContext.SetTagFactory(tagProcessorFactory);
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
// get an ICssResolver and add the custom CSS
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
cssResolver.AddCss(CSSSource, "utf-8", true);
var cssResolverPipeline = new CssResolverPipeline(
cssResolver, htmlPipeline
);
var worker = new XMLWorker(cssResolverPipeline, true);
var parser = new XMLParser(worker);
using (var stringReader = new StringReader(HTMLSource))
{
parser.Parse(stringReader);
document.Close();
HttpContext.Current.Response.ContentType = "application /pdf";
if (base.View)
HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
else
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.WriteFile(OutputPath);
HttpContext.Current.Response.End();
}
}
}
cast(REGEXP_REPLACE(NameNumber, '[^0-9]', '') as UNSIGNED)
I successfully imported lodash in my project with the following commands:
npm install lodash --save
typings install lodash --save
Then i imported it in the following way:
import * as _ from 'lodash';
and in systemjs.config.js i defined this:
map: { 'lodash' : 'node_modules/lodash/lodash.js' }
I work in PHP and use a function to decode the binary data sent back from the server. I extract the information an input to a simple file.php and view the file through my server and all browser display the pdf artefact.
<?php
$data = 'dfjhdfjhdfjhdfjhjhdfjhdfjhdfjhdfdfjhdf==blah...blah...blah..'
$data = base64_decode($data);
header("Content-type: application/pdf");
header("Content-Length:" . strlen($data ));
header("Content-Disposition: inline; filename=label.pdf");
print $data;
exit(1);
?>
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
I don't know a way to do what you want exactly, but a workaround might be:
run: ./prog
./prog $(ARGS)
Then:
make ARGS="asdf" run
# or
make run ARGS="asdf"
you just provide one <folder>
argument to npm install
, argument should point toward the local folder instead of the package name:
npm install /path
To remove just a few specific files from being tracked:
git update-index --assume-unchanged path/to/file
If ever you want to start tracking it again:
git update-index --no-assume-unchanged path/to/file
For Android there is the addition of target-density tag.
target-densitydpi=device-dpi
So, the code would look like
<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />
Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.
Just append a hash with an ID of an element to the URL. E.g.
<div id="about"></div>
and
http://mysite.com/#about
So the link would look like:
<a href="http://mysite.com/#about">About</a>
or just
<a href="#about">About</a>
There are lots of differences between ISO 8601 and RFC 3339. Here is some examples to give you an idea:
2020-12-09T16:09:53+00:00
is a date time value that is compliant both both standards.
2020-12-09 16:09:53+00:00
uses a space to separate the date and time. This is allowed by RFC 3339 but not allowed by ISO 8601.
2020-12-09T16:09:53-00:00
has a negative sign in the time offset. This is allowed by RFC 3339 but not allowed by ISO 8601.
20201209T160953Z
omits the hyphens. This is allowed by ISO 8601 but not allowed by RFC 3339.
ISO 8601 allows for things like ordinal dates such as 2020-344
which represents the 344th day of year 2020. RFC 3339 doesn't allow for that.
For your questions:
Is one just an extension?
No. As shown above each standard supports syntax variations not supported by the the other standard. So one syntax is not a superset or an extension of the other.
Should I use one over the other?
Of course this depends on your scenario. A safe general strategy is to generate date time strings that are valid by both standards.
Another good general strategy is to use an existing standard library for parsing/formatting date time strings and not write custom implementations unless you are addressing a genuinely custom scenario.
Do I really need to care that bad?
Well, that's up to you. Most regular developers who deal with date time strings should have a high level understanding but don't need to dive into the details.
The new version is hard to find. Select the app, then look for "3 dot menu" in upper right corner.
There is a circumstance where you're required to declare it final --otherwise it will result in compile error--, namely passing them through into anonymous classes. Basic example:
public FileFilter createFileExtensionFilter(final String extension) {
FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(extension);
}
};
// What would happen when it's allowed to change extension here?
// extension = "foo";
return fileFilter;
}
Removing the final
modifier would result in compile error, because it isn't guaranteed anymore that the value is a runtime constant. Changing the value from outside the anonymous class would namely cause the anonymous class instance to behave different after the moment of creation.
I wrote this one today while trying to recreate _.sortBy
in TypeScript, and thought I would leave it for anyone in need.
// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key]
export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
return list.sort((a, b): number => {
const _a = getKeyValue<keyof T, T>(index)(a)
const _b = getKeyValue<keyof T, T>(index)(b)
if (_a < _b) return -1
if (_a > _b) return 1
return 0
})
}
It expects an array of generic type T, hence the cast for <T extends {}>
, as well as typing the parameter and function return type with T[]
const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)
** getByKey
fn found here
You can also do something:
SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))
Output:
34512367.392000000
Using jQuery you can achieve this by doing
var cw = $('.child').width();
$('.child').css({'height':cw+'px'});
I had similar problems as well. I put the following line of code in the head of my layout file and all seems to be fine.
<meta http-equiv="X-UA-Compatible" content="IE=9">
From perlfaq8:
How can I sleep() or alarm() for under a second?
If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).
Here's the code that works for me everytime (for Outlook emails):
#to read Subjects and Body of email in a folder (or subfolder)
import win32com.client
#import package
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#create object
#get to the desired folder ([email protected] is my root folder)
root_folder =
outlook.Folders['[email protected]'].Folders['Inbox'].Folders['SubFolderName']
#('Inbox' and 'SubFolderName' are the subfolders)
messages = root_folder.Items
for message in messages:
if message.Unread == True: # gets only 'Unread' emails
subject_content = message.subject
# to store subject lines of mails
body_content = message.body
# to store Body of mails
print(subject_content)
print(body_content)
message.Unread = True # mark the mail as 'Read'
message = messages.GetNext() #iterate over mails
Note: the Nintendo 64 does have a 64-bit processor, however:
Many games took advantage of the chip's 32-bit processing mode as the greater data precision available with 64-bit data types is not typically required by 3D games, as well as the fact that processing 64-bit data uses twice as much RAM, cache, and bandwidth, thereby reducing the overall system performance.
From Webopedia:
The term double precision is something of a misnomer because the precision is not really double.
The word double derives from the fact that a double-precision number uses twice as many bits as a regular floating-point number.
For example, if a single-precision number requires 32 bits, its double-precision counterpart will be 64 bits long.The extra bits increase not only the precision but also the range of magnitudes that can be represented.
The exact amount by which the precision and range of magnitudes are increased depends on what format the program is using to represent floating-point values.
Most computers use a standard format known as the IEEE floating-point format.
The IEEE double-precision format actually has more than twice as many bits of precision as the single-precision format, as well as a much greater range.
From the IEEE standard for floating point arithmetic
Single Precision
The IEEE single precision floating point standard representation requires a 32 bit word, which may be represented as numbered from 0 to 31, left to right.
the final 23 bits are the fraction 'F':
S EEEEEEEE FFFFFFFFFFFFFFFFFFFFFFF
0 1 8 9 31
The value V represented by the word may be determined as follows:
0<E<255
then V=(-1)**S * 2 ** (E-127) * (1.F)
where "1.F" is
intended to represent the binary number created by prefixing F with an
implicit leading 1 and a binary point.V=(-1)**S * 2 ** (-126) * (0.F)
. These
are "unnormalized" values.In particular,
0 00000000 00000000000000000000000 = 0
1 00000000 00000000000000000000000 = -0
0 11111111 00000000000000000000000 = Infinity
1 11111111 00000000000000000000000 = -Infinity
0 11111111 00000100000000000000000 = NaN
1 11111111 00100010001001010101010 = NaN
0 10000000 00000000000000000000000 = +1 * 2**(128-127) * 1.0 = 2
0 10000001 10100000000000000000000 = +1 * 2**(129-127) * 1.101 = 6.5
1 10000001 10100000000000000000000 = -1 * 2**(129-127) * 1.101 = -6.5
0 00000001 00000000000000000000000 = +1 * 2**(1-127) * 1.0 = 2**(-126)
0 00000000 10000000000000000000000 = +1 * 2**(-126) * 0.1 = 2**(-127)
0 00000000 00000000000000000000001 = +1 * 2**(-126) *
0.00000000000000000000001 =
2**(-149) (Smallest positive value)
Double Precision
The IEEE double precision floating point standard representation requires a 64 bit word, which may be represented as numbered from 0 to 63, left to right.
the final 52 bits are the fraction 'F':
S EEEEEEEEEEE FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
0 1 11 12 63
The value V represented by the word may be determined as follows:
0<E<2047
then V=(-1)**S * 2 ** (E-1023) * (1.F)
where "1.F" is
intended to represent the binary number created by prefixing F with an
implicit leading 1 and a binary point.V=(-1)**S * 2 ** (-1022) * (0.F)
These
are "unnormalized" values.Reference:
ANSI/IEEE Standard 754-1985,
Standard for Binary Floating Point Arithmetic.
the best way
map.off();
map.remove();
You should add map.off(), it also works faster, and does not cause problems with the events
select Convert(datetime, '01 ' + Replace('OCT-12', '-', ' '),6)
Additional attributes (in this case, the second onClick
) will be ignored. So, instead of onclick
calling both fbLikeDump();
and WriteCookie();
, it will only call fbLikeDump();
. To fix, simply define a single onclick
attribute and call both functions within it:
<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />
This way is comparatively more easy
SELECT doc_id,serial_number,status FROM date_time ORDER BY date_time DESC LIMIT 0,1;
It basically is higher/greater in everything else. A keyboard is less of a priority than the real time process. This means the process will be taken into account faster then keyboard and if it can't handle that, then your keyboard is slowed.
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
angle = Math.toDegrees(Math.atan2(target.x - x, target.y - y));
now for orientation of circular values to keep angle between 0 and 359 can be:
angle = angle + Math.ceil( -angle / 360 ) * 360
Here is another ThrowIfNull implementation:
[ThreadStatic]
private static string lastMethodName = null;
[ThreadStatic]
private static int lastParamIndex = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowIfNull<T>(this T parameter)
{
var currentStackFrame = new StackFrame(1);
var props = currentStackFrame.GetMethod().GetParameters();
if (!String.IsNullOrEmpty(lastMethodName)) {
if (currentStackFrame.GetMethod().Name != lastMethodName) {
lastParamIndex = 0;
} else if (lastParamIndex >= props.Length - 1) {
lastParamIndex = 0;
} else {
lastParamIndex++;
}
} else {
lastParamIndex = 0;
}
if (!typeof(T).IsValueType) {
for (int i = lastParamIndex; i < props.Length; i++) {
if (props[i].ParameterType.IsValueType) {
lastParamIndex++;
} else {
break;
}
}
}
if (parameter == null) {
string paramName = props[lastParamIndex].Name;
throw new ArgumentNullException(paramName);
}
lastMethodName = currentStackFrame.GetMethod().Name;
}
It's not as efficient as the other impementations, but has cleaner usage:
public void Foo()
{
Bar(1, 2, "Hello", "World"); //no exception
Bar(1, 2, "Hello", null); //exception
Bar(1, 2, null, "World"); //exception
}
public void Bar(int x, int y, string someString1, string someString2)
{
//will also work with comments removed
//x.ThrowIfNull();
//y.ThrowIfNull();
someString1.ThrowIfNull();
someString2.ThrowIfNull();
//Do something incredibly useful here!
}
Changing the parameters to int? will also work.
-bill
The example code below demonstrates this in detail.
<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library
<%
String label = request.getParameter("label"); // retrieving a variable from a previous page
Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null)
{
System.out.println("Connection successful");
}
ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult
%>
<form name="demo form" method="post">
<table>
<tr>
<td>
Label Name:
</td>
<td>
<input type="text" name="label" value="<%=rs.getString("labelname")%>">
</td>
<td>
<select name="label">
<option value="">SELECT</option>
<% while (rs.next()) {%>
<option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
</option>
<%}%>
</select>
</td>
</tr>
</table>
</form>
//The function:
public static ResultSet func(Connection dbc, String x)
{
ResultSet rs = null;
String sql;
PreparedStatement pst;
try
{
sql = "select lname from demo where label like '" + x + "'";
pst = dbc.prepareStatement(sql);
rs = pst.executeQuery();
}
catch (Exception e)
{
e.printStackTrace();
String sqlMessage = e.getMessage();
}
return rs;
}
I have tried to make this example as detailed as possible. Do ask if you have any queries.
Use the sorted()
function:
return sorted(dict.iteritems())
If you want an actual iterator over the sorted results, since sorted()
returns a list, use:
return iter(sorted(dict.iteritems()))
Using CMD you can run your python scripts as long as the installed python is added to the path with the following line:
C: \ Python27;
The (27) is example referring to version 2.7, add as per your version.
Path to system path:
Control Panel => System and Security => System => Advanced Settings => Advanced => Environment Variables.
Under "User Variables," append the PATH variable to the path of the Python installation directory (As above).
Once this is done, you can open a CMD where your scripts are saved, or manually navigate through the CMD.
To run the script enter:
C: \ User \ X \ MyScripts> python ScriptName.py
You can use Application
class(public class in android.application package),that is:
Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
To use this class do:
public class App extends Application {
private static Context mContext;
public static Context getContext() {
return mContext;
}
public static void setContext(Context mContext) {
this.mContext = mContext;
}
...
}
In your manifest:
<application
android:icon="..."
android:label="..."
android:name="com.example.yourmainpackagename.App" >
class that extends Application ^^^
In Activity B:
public class B extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sampleactivitylayout);
App.setContext(this);
...
}
...
}
In class A:
Context c = App.getContext();
Note:
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
First time it WILL NOT start "AfterLoading",
It will just register it to start NEXT Load.
private void Main_Load(object sender, System.EventArgs e)
{
//Register it to Start in Load
//Starting from the Next time.
this.Activated += AfterLoading;
}
private void AfterLoading(object sender, EventArgs e)
{
this.Activated -= AfterLoading;
//Write your code here.
}
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client
.
You could try to run the 2to3
tool on your code, and try to have it translated automatically. References to httplib
will automatically be rewritten to use http.client
instead.
Here is an example to find "all" occurrences of 10 along with the index. Thought this would be of some help.
void _find_all_test()
{
vector<int> ints;
int val;
while(cin >> val) ints.push_back(val);
vector<int>::iterator it;
it = ints.begin();
int count = ints.size();
do
{
it = find(it,ints.end(), 10);//assuming 10 as search element
cout << *it << " found at index " << count -(ints.end() - it) << endl;
}while(++it != ints.end());
}
One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.
Here you go, create a .bat file with the following in it :
@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.
echo.
pause
You should see output like the following:
There should be a newline
inserted here.
Press any key to continue . . .
You only need the code between the REM statements, obviously.
Applets from what I remember do not need a main method, though I am not sure they are technically a program.
// using so that Marshal doesn't have to be qualified
using System.Runtime.InteropServices;
//using for SecureString
using System.Security;
public string DecodeSecureString (SecureString Convert)
{
//convert to IntPtr using Marshal
IntPtr cvttmpst = Marshal.SecureStringToBSTR(Convert);
//convert to string using Marshal
string cvtPlainPassword = Marshal.PtrToStringAuto(cvttmpst);
//return the now plain string
return cvtPlainPassword;
}
I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:
data<- rbind(c(480, 780, 431, 295, 670, 360, 190),
c(720, 350, 377, 255, 340, 615, 345),
c(460, 480, 179, 560, 60, 735, 1260),
c(220, 240, 876, 789, 820, 100, 75))
a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))
data <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
library(ggplot2)
ggplot(data = data, aes(x = Type, y = Time, fill = Group)) +
geom_bar(stat = "identity") +
opts(legend.position = "none")
Well, I think that there are simple solutions than mentioned here on this page! first of all, let's make an example:
You have 1 DIV and want to hide thas DIV on Desktop and show on Mobile (or vice versa). So, let's presume that the DIV position placed in the Head
section and named as header_div
.
The global code in your CSS file
will be: (for the same DIV):
.header_div {
display: none;
}
@media all and (max-width: 768px){
.header_div {
display: block;
}
}
So simple and no need to make 2 div's one for desktop and the other for mobile.
Hope this helps.
Thank you.
Follow these steps to begin using Angular Material.
Step 1: Install Angular Material
npm install --save @angular/material
Step 2: Animations
Some Material components depend on the Angular animations module in order to be able to do more advanced transitions. If you want these animations to work in your app, you have to install the @angular/animations
module and include the BrowserAnimationsModule in your app.
npm install --save @angular/animations
Then
import {BrowserAnimationsModule} from '@angular/platform browser/animations';
@NgModule({
...
imports: [BrowserAnimationsModule],
...
})
export class PizzaPartyAppModule { }
Step 3: Import the component modules
Import the NgModule for each component you want to use:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
})
export class PizzaPartyAppModule { }
be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdCardModule} from '@angular/material';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MdCardModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 4: Include a theme
Including a theme is required to apply all of the core and theme styles to your application.
To get started with a prebuilt theme, include the following in your app's index.html:
<link href="../node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
HTML code
<form class="form-inline" (ngSubmit)="HelloCorp(modelName)">
<div class="select">
<select class="form-control col-lg-8" [(ngModel)]="modelName" required>
<option *ngFor="let corporation of corporations" [ngValue]="corporation">
{{corporation.corp_name}}
</option>
</select>
<button type="submit" class="btn btn-primary manage">Submit</button>
</div>
</form>
Component code
HelloCorp(corporation) {
var corporationObj = corporation.value;
}
Simplest way is to Check the Output - Build tab: It would display the location of war file.
It will have something like:
Installing D:\Project\target\Tool.war to C:\Users\myname.m2\repository\com\tool\1.0\Tool-1.0.war
CSS:
#box{
border:1px solid black;
position:relative;
}
#overlay{
position:absolute;
top:0px;
left:0px;
bottom:0px;
right:0px;
background-color:rgba(255,255,0,0.5);
}
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.
Parameters
target
the sequence to replace.replacement
the replacement
sequence.Returns the resulting string.
Throws NullPointerException
if target or replacement is null.
The first is a much better option.
Parallel.ForEach, internally, uses a Partitioner<T>
to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved.
The second option will schedule a single Task
per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower.
FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.ForEach, if so desired. For details, see Custom Partitioners on MSDN.
The main difference, at runtime, is the second will act asynchronous. This can be duplicated using Parallel.ForEach by doing:
Task.Factory.StartNew( () => Parallel.ForEach<Item>(items, item => DoSomething(item)));
By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.
When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
@Bean
public UserDetailsService userDetailsService() {
List<UserDetails> users= new ArrayList<UserDetails>();
users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
return new InMemoryUserDetailsManager(users);
}
}
So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)
Note: This we should not use in production.
I had the same issue - re-adding the migration and updating the database didn't work and none of the answers above seemed right. Then inspiration hit me - I'm using multiple tiers (one web, one data, and one business). The data layer has the context and all the models. The web layer never threw this exception - it was the business layer (which I set as console application for testing and debugging). Turns out the business layer wasn't using the right connection string to get the db and make the context. So I added the connection string to the app config of the business layer (and the data layer) and viola it works. Putting this here for others who may encounter the same issue.
You may want to look at jQuery Sortable. I used it to reorder table rows.
same as adamb but I would add a dynamic variable num
num = $('.menuFlotante').offset().top;
to get the exact offset or position inside the window to avoid finding the right position.
$(window).bind('scroll', function() {
if ($(window).scrollTop() > num) {
$('.menu').addClass('fixed');
}
else {
num = $('.menuFlotante').offset().top;
$('.menu').removeClass('fixed');
}
});
The JSON format can contain only those types of value:
An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string.
The most common way to achieve that is with what's called base64. Basically, instead of encoding it as 1
and 0
s, it uses a range of 64 characters which makes the textual representation of it more compact. So for example the number '64' in binary is represented as 1000000
, while in base64 it's simply one character: =
.
There are many ways to encode your image in base64 depending on if you want to do it in the browser or not.
Note that if you're developing a web application, it will be way more efficient to store images separately in binary form, and store paths to those images in your JSON or elsewhere. That also allows your client's browser to cache the images.
Try an if statement ...
if @value is null
insert into t (value) values (default)
else
insert into t (value) values (@value)
Use data-dismiss="modal"
. In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal"
is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function
<a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>
In some external script file, and in my doc ready there is of course a function for the click of that identifier ID
$("#divExamListHeader").on('click', '#btnReleaseAll', function () {
// Do DatabaseMagic Here for a call a MVC ActionResult
I think that R is reading the '\' in the string as an escape character. For example \n creates a new line within a string, \t creates a new tab within the string.
'\' will work because R will recognize this as a normal backslash.
You can use div to achieve this. without img tag :) hope this helps.
.img{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
border:1px solid red;_x000D_
background-size:cover;_x000D_
}_x000D_
.img1{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
border:1px solid red;_x000D_
background-size:cover;_x000D_
}
_x000D_
<div class="img"> _x000D_
</div>_x000D_
<div class="img1"> _x000D_
</div>
_x000D_
$('tr').click(function(){
alert( $('tr').index(this) );
});
For first tr
, it alerts 0. If you want to alert 1, you can add 1 to index.
Maybe you find this simpler
select * from (
select ssn, sum(time) from downloads
group by ssn
order by sum(time) desc
) where rownum <= 10 --top 10 downloaders
Regards
K
The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
Just wanted to point out two things that seem inaccurate or at least confusing:
Always persist time according to a unified standard that is not affected by daylight savings. GMT and UTC have been mentioned by different people, though UTC seems to be mentioned most often.
For (almost) all practical computing purposes, UTC is, in fact, GMT. Unless you see a timestamps with a fractional second, you're dealing with GMT which makes this distinction redundant.
Include the local time offset as is (including DST offset) when storing timestamps.
A timestamp is always represented in GMT and thus has no offset.
There is no hard and fast rule.
Here are some rules to make code thread safe in .NET and why these are not good rules:
lock
on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.
Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
You can always use String.format(....). i.e.,
String string = String.format("A String %s %2d", aStringVar, anIntVar);
I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.
For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.
In [8]: arr
Out[8]:
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
In [9]: arr*(arr % 2 == 0).astype(np.int)
Out[9]:
array([[ 0., 2., 0., 4., 0.],
[ 6., 0., 8., 0., 10.]])
Rather than
gb.get_group('foo')
I prefer using gb.groups
df.loc[gb.groups['foo']]
Because in this way you can choose multiple columns as well. for example:
df.loc[gb.groups['foo'],('A','B')]
Use
.title{
display: inline-block;
height: 25px;
}
The only trick is browser support. Check if your list of supported browsers handles inline-block here.
ARM
is a RISC (Reduced Instruction Set Computing) architecture while x86
is a CISC (Complex Instruction Set Computing) one.
The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.
So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.
About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86
isn't specially designed to work with a keyboard neither ARM
for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO
while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.
If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:
An ARM processor is a Reduced Instruction Set Computer (RISC) processor.
Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).
RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.
ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.
An example comparing instruction set architecture:
For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86
repe cmpsb /* repeat while equal compare string bytewise */
while on ARM
shortest form might look like (without error checking etc.)
top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2 /* subtract r2 from r3 and put result into r2 */
beq top /* branch(/jump) if result is zero */
which should give you a hint on how RISC and CISC instruction sets differ in complexity.
Since all the players are numbered I would just use an ArrayList<Player>()
Something like
List<Player> players = new ArrayList<Player>();
System.out.printf("Give the number of the players ");
int number_of_players = scanner.nextInt();
scanner.nextLine(); // discard the rest of the line.
for(int k = 0;k < number_of_players; k++){
System.out.printf("Give the name of player %d: ", k + 1);
String name_of_player = scanner.nextLine();
players.add(new Player(name_of_player,0)); //k=id and 0=score
}
for(Player player: players) {
System.out.println("Name of player in this round:" + player.getName());
I won't argue that it's a good idea (or the semantics of using nullptr
with things that aren't pointers), but it's relatively simple to create a class which would provide "nullable" semantics (see nullable_string).
However, this is a much better fit for C++17's std::optional:
#include <string>
#include <iostream>
#include <optional>
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
if (b)
return "Godzilla";
else
return {};
}
int main()
{
std::cout << "create(false) returned "
<< create(false).value_or("empty") << std::endl;
// optional-returning factory functions are usable as conditions of while and if
if (auto str = create(true))
{
std::cout << "create(true) returned " << *str << std::endl;
}
}
std::optional
, as shown in the example, is convertible to bool
, or you may use the has_value()
method, has exceptions for bad access, etc. This provides you with nullable semantics, which seems to be what Maria was trying to accomplish.
And if you don't want to wait around for C++17 compatibility, see this answer about Boost.Optional.
I can confirm this is a terminfo issue. This is what worked for me. SSH in to the remote machine and run
sudo apt-get install ncurses-term
Boom. Problem solved.
On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".
Hope this helps.
Try this out:
INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
Hope this helps.
This will work too:
$('<li>').text('hello').appendTo('#mylist');
It feels more like a jquery way with the chained function calls.
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
btnMybutton.getBackground().setAlpha(45);
Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)
First of all, you're testing fp
twice. so printf("Error Reading File\n");
never gets executed.
Then, the output of fscanf
should be equal to 2
since you're reading two values.
I just went throughout this and I hovering here for an answer.. In my case the solution was to clear the browser history.
this
can be omitted. All you need to get the current class name is:
GetType().Name
I simple made a careless mistake of forgetting to actually apply the migration (migrate) after making migrations. Writing this just in case anyone might make the same mistake.
http://phonegap.com/blog/2012/03/19/phonegap-cordova-and-whate28099s-in-a-name/
I think this url explains what you need. Phonegap is built on Apache Cordova nothing else. You can think of Apache Cordova as the engine that powers PhoneGap. Over time, the PhoneGap distribution may contain additional tools and thats why they differ in command But they do same thing.
EDIT: Extra info added as its about command difference and what phonegap can do while apache cordova can't or viceversa
First of command line option of PhoneGap
http://docs.phonegap.com/en/edge/guide_cli_index.md.html
Apache Cordova Options http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface
As almost most of commands are similar. There are few differences (Note: No difference in Codebase)
Adobe can add additional features to PhoneGap so that will not be in Cordova ,Eg: Building applications remotely for that you need to have account on https://build.phonegap.com
Though For local builds phonegap cli uses cordova cli (Link to check: https://github.com/phonegap/phonegap-cli/blob/master/lib/phonegap/util/platform.js)
Platform Environment Names. Mapping:
'local' => cordova-cli
'remote' => PhoneGap/Build
Also from following repository: Modules which requires cordova are:
build
create
install
local install
local plugin add , list , remove
run
mode
platform update
run
Which dont include cordova:
remote build
remote install
remote login,logout
remote run
serve
info registers
shows all the registers; info registers eax
shows just the register eax
. The command can be abbreviated as i r
The rouine is pretty good, however it causes my app to hang, so I needed to add the case:
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<xsl:value-of select="$text" />
<!-- Prevent thsi routine from hanging -->
</xsl:when>
before the function gets called recursively.
I got the answer from here: When test hanging in an infinite loop
Thank you!
To my experience, using SINGLE_USER helps most of the times, however, one should be careful: I have experienced occasions in which between the time I start the SINGLE_USER command and the time it is finished... apparently another 'user' had gotten the SINGLE_USER access, not me. If that happens, you're in for a tough job trying to get the access to the database back (in my case, it was a specific service running for a software with SQL databases that got hold of the SINGLE_USER access before I did).
What I think should be the most reliable way (can't vouch for it, but it is what I will test in the days to come), is actually:
- stop services that may interfere with your access (if there are any)
- use the 'kill' script above to close all connections
- set the database to single_user immediately after that
- then do the restore
For Tomcat 7 to increase memory :
Identify your service name, you will find it in the service properties, under the "Path to executable" at the end of the line
For me it is //RS//Tomcat70 so the name is Tomcat70
Then write as administrator :
tomcat7.exe //US//Tomcat70 --JvmOptions=-Xmx1024M
int a = 10;
To get the address of a, you do: &a
(address of a
) which returns an int*
(pointer to int)
int *p = &a;
Then you store the address of a in p
which is of type int*
.
Finally, if you do &p
you get the address of p
which is of type int**
, i.e. pointer to pointer to int:
int** p_ptr = &p;
just seen your edit:
to print out the pointer's address, you either need to convert it:
printf("address of pointer is: 0x%0X\n", (unsigned)&p);
printf("address of pointer to pointer is: 0x%0X\n", (unsigned)&p_ptr);
or if your printf supports it, use the %p
:
printf("address of pointer is: %p\n", p);
printf("address of pointer to pointer is: %p\n", p_ptr);
Swift 2.0:
The proper way to do this kind of type introspection would be with the Mirror struct,
let stringObject:String = "testing"
let stringArrayObject:[String] = ["one", "two"]
let viewObject = UIView()
let anyObject:Any = "testing"
let stringMirror = Mirror(reflecting: stringObject)
let stringArrayMirror = Mirror(reflecting: stringArrayObject)
let viewMirror = Mirror(reflecting: viewObject)
let anyMirror = Mirror(reflecting: anyObject)
Then to access the type itself from the Mirror
struct you would use the property subjectType
like so:
// Prints "String"
print(stringMirror.subjectType)
// Prints "Array<String>"
print(stringArrayMirror.subjectType)
// Prints "UIView"
print(viewMirror.subjectType)
// Prints "String"
print(anyMirror.subjectType)
You can then use something like this:
if anyMirror.subjectType == String.self {
print("anyObject is a string!")
} else {
print("anyObject is not a string!")
}
In my case, the tomcat directory was owned by root, and I was not running eclipse as root.
So I had to
sudo chown -R $USER apache-tomcat-VERSION/
The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.
All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild()
method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].
Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:
Step 1:
In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".
Step 2 Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
</TextView>
BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.
Step 3
In your onCreate
method, do this :
FrameLayout frameLayout = findViewById(R.id.container);
TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
frameLayout.addView(textView);
(Note that setting last parameter of findViewById
to null
and adding view by calling addView()
on container view (frameLayout) is same as simply attaching the inflated view by passing true
in 3rd parameter of findViewById()
. For more, see this.)
That answer really helped me, in my case i had to filter some elements out and have special aligment on their error div,
errorPlacement:function(error,element) {
if (element.attr("id") == "special_element") {
// special align
} else { // default error scheme
error.insertAfter(element);
}
}
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
Does replacing a character in a String with a null character even work in Java?
No.
Would this be the culprit to the funky characters?
Quite likely.
While UNC path is supported since Git 2.21 (Feb. 2019, see below), Git 2.24 (Q4 2019) will allow
git clone file://192.168.10.51/code
No more file:////xxx
, 'file://
' is enough to refer to an UNC path share.
See "Git Fetch Error with UNC".
Note, since 2016 and the MingW-64 git.exe
packaged with Git for Windows, an UNC path is supported.
(See "How are msys, msys2, and MinGW-64 related to each other?")
And with Git 2.21 (Feb. 2019), this support extends even in in an msys2 shell (with quotes around the UNC path).
See commit 9e9da23, commit 5440df4 (17 Jan 2019) by Johannes Schindelin (dscho
).
Helped-by: Kim Gybels (Jeff-G
).
(Merged by Junio C Hamano -- gitster
-- in commit f5dd919, 05 Feb 2019)
Before Git 2.21, due to a quirk in Git's method to spawn git-upload-pack
, there is a
problem when passing paths with backslashes in them: Git will force the
command-line through the shell, which has different quoting semantics in
Git for Windows (being an MSYS2 program) than regular Win32 executables
such as git.exe
itself.
The symptom is that the first of the two backslashes in UNC paths of the
form \\myserver\folder\repository.git
is stripped off.
This is mitigated now:
mingw: special-case arguments to
sh
The MSYS2 runtime does its best to emulate the command-line wildcard expansion and de-quoting which would be performed by the calling Unix shell on Unix systems.
Those Unix shell quoting rules differ from the quoting rules applying to Windows' cmd and Powershell, making it a little awkward to quote command-line parameters properly when spawning other processes.
In particular,
git.exe
passes arguments to subprocesses that are not intended to be interpreted as wildcards, and if they contain backslashes, those are not to be interpreted as escape characters, e.g. when passing Windows paths.Note: this is only a problem when calling MSYS2 executables, not when calling MINGW executables such as git.exe. However, we do call MSYS2 executables frequently, most notably when setting the
use_shell
flag in the child_process structure.There is no elegant way to determine whether the
.exe
file to be executed is an MSYS2 program or a MINGW one.
But since the use case of passing a command line through the shell is so prevalent, we need to work around this issue at least when executingsh.exe
.Let's introduce an ugly, hard-coded test whether
argv[0]
is "sh
", and whether it refers to the MSYS2 Bash, to determine whether we need to quote the arguments differently than usual.That still does not fix the issue completely, but at least it is something.
Incidentally, this also fixes the problem where
git clone \\server\repo
failed due to incorrect handling of the backslashes when handing the path to thegit-upload-pack
process.Further, we need to take care to quote not only whitespace and backslashes, but also curly brackets.
As aliases frequently go through the MSYS2 Bash, and as aliases frequently get parameters such asHEAD@{yesterday}
, this is really important.
Best one in my experience is https://github.com/mathiasbynens/jquery-placeholder (recommended by html5please.com). http://afarkas.github.com/webshim/demos/index.html also has a good solution among its much more extensive library of polyfills.
You can pass data to the view using the with method.
return view('greeting', ['name' => 'James']);
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
In the folder where you installed Anaconda (Example: C:\Users\username\Anaconda3
) there should be an executable called Uninstall-Anaconda.exe
. Double click on this file to start uninstall Anaconda.
That should do the trick as well.
It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr()
method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]
IE has some problems with the DOM setAttribute
method but in this case it should be fine:
this.setAttribute("checked", "checked");
In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked
attribute, you need to set the checked
property as well:
this.setAttribute("checked", "checked");
this.checked = true;
To uncheck the checkbox and remove the attribute, do the following:
this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
One idea is to use String... args
public class Sample {
void demoMethod(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
public static void main(String args[] ) {
new Sample().demoMethod("ram", "rahim", "robert");
new Sample().demoMethod("krishna", "kasyap");
new Sample().demoMethod();
}
}
Output
ram
rahim
robert
krishna
kasyap
from https://www.tutorialspoint.com/Does-Java-support-default-parameter-values-for-a-method
This works perfectly for adding rows and controls in a TableLayoutPanel.
Define a blank Tablelayoutpanel with 3 columns in the design page
Dim TableLayoutPanel3 As New TableLayoutPanel()
TableLayoutPanel3.Name = "TableLayoutPanel3"
TableLayoutPanel3.Location = New System.Drawing.Point(32, 287)
TableLayoutPanel3.AutoSize = True
TableLayoutPanel3.Size = New System.Drawing.Size(620, 20)
TableLayoutPanel3.ColumnCount = 3
TableLayoutPanel3.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
TableLayoutPanel3.BackColor = System.Drawing.Color.Transparent
TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 26.34146!))
TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 73.65854!))
TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 85.0!))
Controls.Add(TableLayoutPanel3)
Create a button btnAddRow to add rows on each click
Private Sub btnAddRow_Click(sender As System.Object, e As System.EventArgs) Handles btnAddRow.Click
TableLayoutPanel3.GrowStyle = TableLayoutPanelGrowStyle.AddRows
TableLayoutPanel3.RowStyles.Add(New RowStyle(SizeType.Absolute, 20))
TableLayoutPanel3.SuspendLayout()
TableLayoutPanel3.RowCount += 1
Dim tb1 As New TextBox()
Dim tb2 As New TextBox()
Dim tb3 As New TextBox()
TableLayoutPanel3.Controls.Add(tb1 , 0, TableLayoutPanel3.RowCount - 1)
TableLayoutPanel3.Controls.Add(tb2, 1, TableLayoutPanel3.RowCount - 1)
TableLayoutPanel3.Controls.Add(tb3, 2, TableLayoutPanel3.RowCount - 1)
TableLayoutPanel3.ResumeLayout()
tb1.Focus()
End Sub
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
Just go into npm page and follow the instructions.
Hello I had the same problem but I tried many different states and I came to it: SOURCE doesn't work with ; at the end in my case:
SOURCE D:\Barname-Narmafzar\computer programming's languages\SQL\MySQL\dataAug-12-2019\dataAug-12-2019.sql;
and the error was:
ERROR: Unknown command '\B'.
'>
it also didn't work with a quotation for the address.
But it works without ; at the end:
SOURCE D:\Barname-Narmafzar\computer programming's languages\SQL\MySQL\dataAug-12-2019\dataAug-12-2019.sql
But remember to use USE database_name; before that. I think it's so because the SOURCE or USE or HELP are for the Mysql itself and they are not such query codes although when you write HELP it says:
"Note that all text commands must be first on line and end with ; ".
but here doesn't work.
I should say that I have done it in CMD and I didn't try it in Mysql Workbench. That was it
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
Update 1: There is a CSS3 spec for CSS level 3 nesting. It's currently a draft. https://tabatkins.github.io/specs/css-nesting/
Update 2 (2019): We now have a CSSWG draft https://drafts.csswg.org/css-nesting-1/
If approved, the syntax would look like this:
table.colortable {
& td {
text-align:center;
&.c { text-transform:uppercase }
&:first-child, &:first-child + td { border:1px solid black }
}
& th {
text-align:center;
background:black;
color:white;
}
}
.foo {
color: red;
@nest & > .bar {
color: blue;
}
}
.foo {
color: red;
@nest .parent & {
color: blue;
}
}
Status: The original 2015 spec proposal was not approved by the Working Group.
Do configure --help
and see what other options are available.
It is very common to provide different options to override different locations. By standard, --prefix
overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.
The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:
./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc
I believe that should do it.
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
Static members need to be initialized in a .cpp translation unit at file scope or in the appropriate namespace:
const string foo::s( "my foo");
SL_CTX_use_PrivateKey("/etc/nginx/ssl/file") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)
This error can happen, when the certificate private key (ssl_certificate_key
, e.g. .key
or .pem
file) does not match the public certificate file (ssl_certificate
) in your Nginx configuration (check nginx.conf
or in sites-enabled/
). Make sure both files are matching.
Check Nginx error logs for further details (e.g. /var/log/nginx/error.log
).
You can also use an oracle defined collection
DECLARE
arrayvalues sys.odcivarchar2list;
BEGIN
arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
FOR x IN ( SELECT m.column_value m_value
FROM table(arrayvalues) m )
LOOP
dbms_output.put_line (x.m_value||' is a good pal');
END LOOP;
END;
I would use in-memory array. But with the .COUNT
improvement suggested by uziberia:
DECLARE
TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
arrayvalues t_people;
BEGIN
SELECT *
BULK COLLECT INTO arrayvalues
FROM (select 'Matt' m_value from dual union all
select 'Joanne' from dual union all
select 'Robert' from dual
)
;
--
FOR i IN 1 .. arrayvalues.COUNT
LOOP
dbms_output.put_line(arrayvalues(i)||' is my friend');
END LOOP;
END;
Another solution would be to use a Hashmap like @Jchomel did here.
NB:
With Oracle 12c you can even query arrays directly now!
Another solution is to use getDocumentById
and insertAdjacentHTML
.
Code:
function addRow() {
const div = document.getElementById('content');
div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');
}
Check here, for more details: Element.insertAdjacentHTML()
/**
* Not applicable to Static Inner Class (nested class)
*/
public static Object getDeclaringTopLevelClassObject(Object object) {
if (object == null) {
return null;
}
Class cls = object.getClass();
if (cls == null) {
return object;
}
Class outerCls = cls.getEnclosingClass();
if (outerCls == null) {
// this is top-level class
return object;
}
// get outer class object
Object outerObj = null;
try {
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (field != null && field.getType() == outerCls
&& field.getName() != null && field.getName().startsWith("this$")) {
field.setAccessible(true);
outerObj = field.get(object);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return getDeclaringTopLevelClassObject(outerObj);
}
Of course, the name of the implicit reference is unreliable, so you shouldn't use reflection for the job.
This is because h1
is a block element, so it will extend across the line (or the width you give).
You can make the border go only around the text by setting display:inline
on the h1
I recently ran into this kinda issue, where I need to communicate between client and server using websocket in a PHP based codeigniter project.
I resolved this issue by adding my port(node app running on) into Allow incoming TCP ports
& Allow outgoing TCP ports
lists.
You can find these configurations in Firewall Configurations
in your server's WHM panel.
R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat
.
y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab: , newline:
## , unicode point: €
Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1
To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.
grepl("\\[", "a[b")
## [1] TRUE
To match backslashes, you need to double escape, resulting in four backslashes.
grepl("\\\\", c("a\\b", "a\nb"))
## [1] TRUE FALSE
The rebus
package contains constants for each of the special characters to save you mistyping slashes.
library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"
For more examples see:
?SpecialCharacters
Your problem can be solved this way:
library(rebus)
grepl(OPEN_BRACKET, "a[b")
You can also wrap the special characters in square brackets to form a character class.
grepl("[?]", "a?b")
## [1] TRUE
Two of the special characters have special meaning inside character classes: \
and ^
.
Backslash still needs to be escaped even if it is inside a character class.
grepl("[\\\\]", c("a\\b", "a\nb"))
## [1] TRUE FALSE
Caret only needs to be escaped if it is directly after the opening square bracket.
grepl("[ ^]", "a^b") # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b")
## [1] TRUE
rebus
also lets you form a character class.
char_class("?")
## <regex> [?]
If you want to match all punctuation, you can use the [:punct:]
character class.
grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE
stringi
maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.
stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
You can also use the cross-platform syntax for accessing a UGC.
stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
Placing characters between \\Q
and \\E
makes the regular expression engine treat them literally rather than as regular expressions.
grepl("\\Q.\\E", "a.b")
## [1] TRUE
rebus
lets you write literal blocks of regular expressions.
literal(".")
## <regex> \Q.\E
Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:
grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")
Therefore, before starting '$ sqlplus' on OS, run the followings:
On Windows
set NLS_LANG=AMERICAN_AMERICA.UTF8
On Unix (Solaris and Linux, centos etc)
export NLS_LANG=AMERICAN_AMERICA.UTF8
It would also be advisable to set env variable in your '.bash_profile' [on start up script]
This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.
just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.
For me it doesn't make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.
One also doesn't silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.
Use this command.
mvn package
to make the package jar file. Then, run this command.
java -cp target/artifactId-version-SNAPSHOT.jar package.Java-Main-File-Name
type your own artifactId, version and package and java main file.
I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:
[filename] = sys.argv[1:]
in_file = open(filename) # Don't need the "r"
This will assign the one argument to filename
and raise an exception if there isn't exactly one argument.
Putting the condition in the join seems "semantically wrong" to me, as that's not what JOINs are "for". But that's very qualitative.
Additional problem: if you decide to switch from an inner join to, say, a right join, having the condition be inside the JOIN could lead to unexpected results.
The @Url.Action()
method is proccess on the server-side
, so you cannot pass a client-side
value to this function as a parameter. You can concat the client-side
variables with the server-side
url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer")
is processed on the server-side
and the rest of the string is processed on the client-side
, concatenating the result of the server-side
method with the client-side
.
There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform !
Use [NSIndexPath indexPathForRow:inSection:]
to quickly create an index path.
Edit: In Swift 3:
let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
Swift 5
IndexPath(row: 0, section: 0)
One-liner using String.replace with callback (no emoji support):
// 0 - index to replace, 'f' - replacement string
'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
// "fog"
Explained:
//String.replace will call the callback on each pattern match
//in this case - each character
'dog'.replace(/./g, function (character, index) {
if (index == 0) //we want to replace the first character
return 'f'
return character //leaving other characters the same
})
In order to include a global library, eg jquery.js
file in the scripts array from angular-cli.json
(angular.json
when using angular 6+):
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
After this, restart ng serve if it is already started.
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
You cannot upload like this.
http://grand-shopping.com/<"some folder">
You need a physical path exactly like in your local
C:/Users/puneet verma/Downloads/
What you can do is create some local path where your server is working. Hence you can store and retrieve the file. If you bought some domain from any websites there will be path to upload the files. You create these variable as static constant and use it based on the server you are working (Local/Website).
An Alternative to using an API is to use HTML 5 location Navigator to query the browser about the User location. I was looking for a similar approach as in the subject question but I found that HTML 5 Navigator works better and cheaper for my situation. Please consider that your scinario might be different. To get the User position using Html5 is very easy:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
console.log("Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude);
}
Try it yourself on W3Schools Geolocation Tutorial
Using ES6, URL API and URLSearchParams API.
function objectifyQueryString(url) {
let _url = new URL(url);
let _params = new URLSearchParams(_url.search);
let query = Array.from(_params.keys()).reduce((sum, value)=>{
return Object.assign({[value]: _params.get(value)}, sum);
}, {});
return query;
}
In your Eclipse editor screen, try Control + Shift + R buttons.
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
Hit F4 and you'll get what you are looking for.
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')
A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.
If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?
this.props.location
is a react-router feature, you'll have to install if you want to use it.
Note: doesn't return the full url.
Break down the algorithm into pieces you know the big O notation for, and combine through big O operators. That's the only way I know of.
For more information, check the Wikipedia page on the subject.
I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
Create an XML file named border.xml in the drawable folder and put the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
Then add a background to your linear layout like this:
android:background="@drawable/border"
EDIT :
This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:
ALSO
tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :
Finally its works perfectly with all APIs
EDIT 2 :
It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="0dp" android:right="0dp" android:top="0dp"
android:bottom="-10dp">
<shape android:shape="rectangle">
<stroke android:width="10dp" android:color="#B22222" />
</shape>
</item>
</layer-list>
hope this help .
Use this example
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-GB",true);
decimal currency_usd = decimal.Parse(GetRateFromCbrf("usd"),culInfo);
decimal currency_eur = decimal.Parse(GetRateFromCbrf("eur"), culInfo);
Just loop...
foreach(var table in DataSet1.Tables) {
foreach(var col in table.Columns) {
...
}
foreach(var row in table.Rows) {
object[] values = row.ItemArray;
...
}
}
Kinda little late but I tried to extend @Tobia's answer to set the layout "horizontal" or "vertical" driven by the command argument e.g.
{"keys": ["f6"], "command": "split_pane", "args": {"split_type": "vertical"} }
Plugin code:
import sublime_plugin
class SplitPaneCommand(sublime_plugin.WindowCommand):
def run(self, split_type):
w = self.window
if w.num_groups() == 1:
if (split_type == "horizontal"):
w.run_command('set_layout', {
'cols': [0.0, 1.0],
'rows': [0.0, 0.33, 1.0],
'cells': [[0, 0, 1, 1], [0, 1, 1, 2]]
})
elif (split_type == "vertical"):
w.run_command('set_layout', {
"cols": [0.0, 0.46, 1.0],
"rows": [0.0, 1.0],
"cells": [[0, 0, 1, 1], [1, 0, 2, 1]]
})
w.focus_group(0)
w.run_command('clone_file')
w.run_command('move_to_group', {'group': 1})
w.focus_group(1)
else:
w.focus_group(1)
w.run_command('close')
w.run_command('set_layout', {
'cols': [0.0, 1.0],
'rows': [0.0, 1.0],
'cells': [[0, 0, 1, 1]]
})
How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?
If you're linking with -lfoo
then the library is likely libfoo.so
. The library itself is probably part of the libfoo
package, and the headers are in the libfoo-dev
package as you've discovered.
Some people use the GUI "synaptic" app (sudo synaptic
) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that apt-get
supports bash completion.
Try typing sudo apt-get install libssl
and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).
Bash completion is actually very useful... for example, you can also get a list of commands that apt-get
supports by typing sudo apt-get
and then hitting tab.
Your code is passing a function as an argument to find
. That function takes an element
argument (of type Conversation
) and returns void
(meaning there is no return value). TypeScript describes this as (element: Conversation) => void'
What TypeScript is saying is that the find
function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations
, a number
and a Conversation
array, and that this function should return a boolean
.
So bottom line is that you either need to change your code to pass in the values to find
correctly, or else you need to provide an overload to the definition of find
in your definition file that accepts a Conversation
and returns void
.
You have two options
INNER JOIN x
ON x.qid = y.qid OR (x.qid IS NULL AND y.qid IS NULL)
or easier
INNER JOIN x
ON x.qid IS NOT DISTINCT FROM y.qid
They are technically the same thing, it's actually a different notation of using the provider
function of the $provide
service.
The only difference between the service
and the factory
notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.
// Factory
angular.module('myApp').factory('myFactory', function() {
var _myPrivateValue = 123;
return {
privateValue: function() { return _myPrivateValue; }
};
});
// Service
function MyService() {
this._myPrivateValue = 123;
}
MyService.prototype.privateValue = function() {
return this._myPrivateValue;
};
angular.module('myApp').service('MyService', MyService);
For Kotlin:
val password = EditText(this)
password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
password.hint = "Password"
This can be caused by incorrect app-ID
In my ionic sample I had the same issue because I had inserted a different "app-ID" in my ionic app other than the app-ID I received from Facebook developer account.
so we have to carefully insert the relavent appID
This solution works for both physical devices and iOS simulator in a way that simulator returns the same model as physical device would return for a model e.g. "iPhone10,6" for iPhone X (GSM) rather than "x86_64".
Definition - Swift 4:
import UIKit
extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
if let value = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
return value
} else {
return identifier
}
}
}
Usage:
print(UIDevice.current.modelName)
Use this
DELETE FROM `articles`, `comments`
USING `articles`,`comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
or
DELETE `articles`, `comments`
FROM `articles`, `comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
I understand you want to open a xml file using php. That's called to parse a xml file. The best reference is here.
public static T isNull<T>(this T v1, T defaultValue)
{
return v1 == null ? defaultValue : v1;
}
myValue.isNull(new MyValue())
If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:
if(document.getElementById("yourid") !== null)
{
}
getElementById
returns null
if it can't be found.
If however you plan to use the jQuery object later i'd suggest:
$(document).ready(function() {
var $myDiv = $('#DivID');
if ( $myDiv.length){
//you can now reuse $myDiv here, without having to select it again.
}
});
A selector always returns a jQuery object, so there shouldn't be a need to check against null
(I'd be interested if there is an edge case where you need to check for null
- but I don't think there is).
If the selector doesn't find anything then length === 0
which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"
In Eclipse
, go to File
-> Switch Workspace
, choose or create a new workspace.
A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.
Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.
Hope the explanation is clear enough.
I find you need the following:
I would recommend using a Double not a double as your type then you check against null.
The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.
To return information, like your number, use
echo "$value"
To print additional information that you don't want captured, use
echo "my irrelevant info" >&2
Finally, to capture it, use what you did:
result=$(password_formula)
In other words:
echo "enter: "
read input
password_formula()
{
length=${#input}
last_two=${input:length-2:length}
first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
let sum=$first+$second
sum_len=${#sum}
echo $second >&2
echo $sum >&2
if [ $sum -gt 9 ]
then
sum=${sum:1}
fi
value=$second$sum$first
echo $value
}
result=$(password_formula)
echo "The value is $result"
You can just use
myDict = {
"P1": (lambda x: function1()),
"P2": (lambda x: function2()),
...,
"Pn": (lambda x: functionn())}
myItems = ["P1", "P2", ..., "Pn"]
for item in myItems:
myDict[item]()
I know this is an old thread but I feel this really needs saying and don't have anywhere else to say it. For everybody here, use goto. I just used it.
Like almost everything, goto is not 100% either/xor "bad" or "good". There are at least two uses where I'd say that if you use a goto for them - and don't use it for anything else - you should not only be 100% okay, but your program will be even more readable than without it, as it makes your intention that much clearer (there are ways to avoid it, but I've found all of them to be much clunkier):
Instead of just dogmatically accepting rules like "so-so is 'evil'", understand why that sentiment is claimed, and follow the "why", not the letter of the sentiment. Not knowing this got me in a lot of trouble, too, to the point I'd say calling things dogmatically "evil" can be more harmful than the thing itself. At worst, you just get bad code - and then you know you weren't using it right so long as you heard to be wary, but if you are wracking yourself trying to satisfy the dogmatism, I'd say that's worse.
Why "goto" is called "evil" is because you should never use it to replace ordinary ifs, fors, and whiles. And why that? Try it, try using "goto" instead of ordinary control logic statements, all the time, then try writing the same code again with the control logic, and tell me which one looks nicer and more understandable, and which one looks more like a mess. There you go. (Bonus: try and add a new feature now to the goto-only code.) That's why it's "evil", with suitable scope qualification around the "evil". Using it to short-circuit the shortcomings of C's "break
" command is not a problematic usage, so long as you make it clear from the code what your goto is supposed to accomplish (e.g. using a label like "nestedBreak" or something). Breaking out of a nested loop is very natural.
(Or to put it more simply: Use goto to break out of the loop. I'd say that's even preferable. Don't use goto to create the loop. That's "evil".)
And how do you know if you're being dogmatic? If following an "xyz is evil" rule leads your code to be less understandable because you're contorting yourself trying to get around it (such as by adding extra conditionals on each loop, or some flag variable, or some other trick like that), then you're quite likely being dogmatic.
There's no substitute for learning good thinking habits, moreso than good coding habits. The former are prior to the latter and the latter will often follow once the former are adopted. The problem is, however, that far too often I find, the latter are not explicated enough. Too many simply say "this is bad" and "this needs more thought" without saying what to think, what to think about, and why. And that's a big shame.
(FWIW, in C++, the need to break out of nested loops still exists, but the need for error codes does not: in that case, always use exceptions to handle error codes, never return them unless it's going to be so frequent that the exception throw and catch will be causing a performance problem, e.g. in a tight loop in a high demand server code, perhaps [some may say that 'exceptions' should be 'used rarely' but that's another part of ill-thought-out dogmatism: no, at least in my experience after bucking that dogma I find they make things much clearer - just don't abuse them to do something other than error handling, like using them as control flow; effectively the same as with "goto". If you use them all and only for error handling, that's what they're there for.].)
Consider this:
function group1k(s) {
return (""+s)
.replace(/(\d+)(\d{3})(\d{3})$/ ,"$1 $2 $3" )
.replace(/(\d+)(\d{3})$/ ,"$1 $2" )
.replace(/(\d+)(\d{3})(\d{3})\./ ,"$1 $2 $3.")
.replace(/(\d+)(\d{3})\./ ,"$1 $2." )
;
}
It's a quick solution for anything under 999.999.999, which is usually enough. I know the drawbacks and I'm not saying this is the ultimate weapon - but it's just as fast as the others above and I find this one more readable. If you don't need decimals you can simplify it even more:
function group1k(s) {
return (""+s)
.replace(/(\d+)(\d{3})(\d{3})$/ ,"$1 $2 $3")
.replace(/(\d+)(\d{3})$/ ,"$1 $2" )
;
}
Isn't it handy.
In oracle, generally speaking, there are number of facts that I will mention in following section:
Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.
However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.
So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:
SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'
Somewhat late to the party, but I included this in my MarkUtils-Web library in WebUtils - Checkstyle-approved and JUnit-tested:
import javax.servlet.http.HttpServletRequest;
public class GetRequestUrl{
/**
* <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
* (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
* that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
* <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
* >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
* @author Mark A. Ziesemer
* <a href="http://www.ziesemer.com."><www.ziesemer.com></a>
*/
public String getRequestUrl(final HttpServletRequest req){
final String scheme = req.getScheme();
final int port = req.getServerPort();
final StringBuilder url = new StringBuilder(256);
url.append(scheme);
url.append("://");
url.append(req.getServerName());
if(!(("http".equals(scheme) && (port == 0 || port == 80))
|| ("https".equals(scheme) && port == 443))){
url.append(':');
url.append(port);
}
url.append(req.getRequestURI());
final String qs = req.getQueryString();
if(qs != null){
url.append('?');
url.append(qs);
}
final String result = url.toString();
return result;
}
}
Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.
See also:
Surprisingly this library not mentioned yet
python package named python-slugify, which does a pretty good job of slugifying:
pip install python-slugify
Works like this:
from slugify import slugify
txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")
txt = 'Nín hao. Wo shì zhong guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")
txt = '?????????'
r = slugify(txt)
self.assertEquals(r, "kompiuter")
txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")
Simply type in command prompt :
set path=%PATH%;D:\xampp\mysql\bin;
Here my path started from D so I used D: , you can use C: or E:
The below code may help you,
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = list.toString();
System.out.println("Step-1 : " + str);
str = str.replaceAll("[\\[\\]]", "");
System.out.println("Step-2 : " + str);
Output:
Step-1 : [1, 2, 3]
Step-2 : 1, 2, 3
It can be done in a safer way.
If your PHP array contains special characters, you need to use rawurlencode() in PHP and then use decodeURIComponent() in JS to escape those. And parse the JSON to native js. Try this:
var data = JSON.parse(
decodeURIComponent(
"<?=rawurlencode(json_encode($data));?>"
)
);
console.log(data);
$ git branch -D <branch-name>
[NOTE]:
-D
is a shortcut for --delete --force
.
set the body max-width:110%; and the make the width on the header 110% it will leave a small margin on left that you can fiX with margin-left: -8px; margin-top: -10px;
This also works:
this.getCurrentFocus()
It gets the view so I can use it.
I only use the forward slash once at the end of each script, to tell sqlplus that there is not more lines of code. In the middle of a script, I do not use a slash.
or
([io.fileinfo]"c:\temp\myfile.txt").basename
or
"c:\temp\myfile.txt".split('\.')[-2]
There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;
html {_x000D_
scroll-behavior: smooth;_x000D_
}_x000D_
_x000D_
a {_x000D_
text-decoration: none;_x000D_
color: black;_x000D_
} _x000D_
_x000D_
#down {_x000D_
margin-top: 100%;_x000D_
padding-bottom: 25%;_x000D_
}
_x000D_
<html>_x000D_
<a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
<div id="down">_x000D_
<h1>You are down!</h1>_x000D_
</div>_x000D_
</html
_x000D_
The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.
Since IPv4 addresses are 4 byte long, you could use an INT
(UNSIGNED
) that has exactly 4 bytes:
`ipv4` INT UNSIGNED
And INET_ATON
and INET_NTOA
to convert them:
INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;
For IPv6 addresses you could use a BINARY
instead:
`ipv6` BINARY(16)
And use PHP’s inet_pton
and inet_ntop
for conversion:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
You can use a std::map
to map the input to your enum
:
#include <iostream>
#include <string>
#include <map>
using namespace std;
enum level {easy, medium, hard};
map<string, level> levels;
void register_levels()
{
levels["easy"] = easy;
levels["medium"] = medium;
levels["hard"] = hard;
}
int main()
{
register_levels();
string input;
cin >> input;
switch( levels[input] )
{
case easy:
cout << "easy!"; break;
case medium:
cout << "medium!"; break;
case hard:
cout << "hard!"; break;
}
}
It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").
You get this message when you've used async in your template, but are referring to an object that isn't an Observable.
So for examples sake, lets' say I had these properties in my class:
job:Job
job$:Observable<Job>
Then in my template, I refer to it this way:
{{job | async }}
instead of:
{{job$ | async }}
You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.
Any of the below three options works for you:
echo[
echo(
echo.
For example:
@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo(
echo The above line is also blank.
echo.
echo The above line is also blank.
try this;
webView.loadData("<iframe src='http://www.google.com' style='border: 0; width: 100%; height: 100%'></iframe>", "text/html; charset=utf-8", "UTF-8");
This worked for me.
def parse_data():
if request.method == "POST":
data = request.get_json()
print(data['answers'])
return render_template('output.html', data=data)
$.ajax({
type: 'POST',
url: "/parse_data",
data: JSON.stringify({values}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
// do something with the received data
}
});
I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.
Basically what you need to do is put your .so
files inside a a folder named lib
(Note: it is not libs
and this is not a mistake). It should be in the same structure it should be in the APK
file.
In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.
So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip
(the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip
file into armeabi.jar
and added the line compile fileTree(dir: 'libs', include: '*.jar')
into dependencies {}
in the gradle's build file.
This solved my problem in a rather clean way.
In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).
So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.
sed 's/foo/$BAR/g'
sed "s/foo/$BAR/g"
In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.
In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file=
as elaborated in the Valgrind's user manual.
Four replacements were available at the time of writing:
%p
: Prints the current process ID
valgrind --log-file="myFile-%p.dat" <application-name>
%n
: Prints file sequence number unique for the current process
valgrind --log-file="myFile-%p-%n.dat" <application-name>
%q{ENV}
: Prints contents of the environment variable ENV
valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
%%
: Prints %
valgrind --log-file="myFile-%%.dat" <application-name>
I have now been able to get Keyboard input in Swift by using the following:
In my main.swift file I declared a variable i and assigned to it the function GetInt() which I defined in Objective C. Through a so called Bridging Header where I declared the function prototype for GetInt I could link to main.swift. Here are the files:
main.swift:
var i: CInt = GetInt()
println("Your input is \(i) ");
Bridging Header:
#include "obj.m"
int GetInt();
obj.m:
#import <Foundation/Foundation.h>
#import <stdio.h>
#import <stdlib.h>
int GetInt()
{
int i;
scanf("%i", &i);
return i;
}
In obj.m it is possible to include the c standard output and input, stdio.h, as well as the c standard library stdlib.h which enables you to program in C in Objective-C, which means there is no need for including a real swift file like user.c or something like that.
Hope I could help,
Edit: It is not possible to get String input through C because here I am using the CInt -> the integer type of C and not of Swift. There is no equivalent Swift type for the C char*. Therefore String is not convertible to string. But there are fairly enough solutions around here to get String input.
Raul