Let's assume
],
is the character where we wanted to break at
notePad++
Find window
Ctrl+F Replace
TabSearch Mode
to Extended
],
in Find What
field\n
in Replace with
field Replace All
I use 3 lines to do this job, so consider $s as your "stuff"...
$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);
str = str.replaceAll("\\r\\n|\\r|\\n", " ");
Worked perfectly for me after searching a lot, having failed with every other line.
Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for INSERT
or UPDATE
operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.
/// <summary>
/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends
/// the specified line to an existing block of text, assumed to have \r\n delimiters, and
/// truncate at a maximum length.
/// </summary>
/// <param name="sNewLine">Single text line to be prepended to existing text</param>
/// <param name="sOrigLines">Current text value; assumed to be CRLF-delimited</param>
/// <param name="iMaxLen">Integer field length</param>
/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations. Empty on error.</returns>
private string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)
{
String fn = MethodBase.GetCurrentMethod().Name;
try
{
String [] line_array = sOrigLines.Split("\r\n".ToCharArray());
List<string> orig_lines = new List<string>();
foreach(String orig_line in line_array)
{
if (!String.IsNullOrEmpty(orig_line))
{
orig_lines.Add(orig_line);
}
} // end foreach(original line)
String final_comments = "'" + sNewLine + "' + CHAR(13) + CHAR(10) ";
int cum_length = sNewLine.Length + 2;
foreach(String orig_line in orig_lines)
{
String curline = orig_line;
if (cum_length >= iMaxLen) break; // stop appending if we're already over
if ((cum_length+orig_line.Length+2)>=iMaxLen) // If this one will push us over, truncate and warn:
{
Util.HandleAppErr(this, fn, "Truncating comments: " + orig_line);
curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));
}
final_comments += " + '" + curline + "' + CHAR(13) + CHAR(10) \r\n";
cum_length += orig_line.Length + 2;
} // end foreach(second pass on original lines)
return(final_comments);
} // end main try()
catch(Exception exc)
{
Util.HandleExc(this,fn,exc);
return("");
}
}
I wrote a little jQuery extension for this:
$.fn.nl2brText = function (sText) {
var bReturnValue = 'undefined' == typeof sText;
if(bReturnValue) {
sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
}
var aElms = [];
sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
if(aElms.length) {
aElms.push(document.createElement('br'));
}
aElms.push(document.createTextNode(sSubstring));
});
var $aElms = $(aElms);
if(bReturnValue) {
return $aElms;
}
return this.empty().append($aElms);
};
For a string I just write "\n"
to give me a new line. For example, typing console.log("First Name: Rex" + "\n" + "Last Name: Blythe");
Will type:
First Name: Rex
Last Name: Blythe
Important to note it's \n
(backslash) rather than /n
.
In PCRE \R
matches \n
, \r
and \r\n
.
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
foreach ($arr as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
true array:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
$array = array(); // inisiasi variable array in format array
foreach ($arr as $line) { // loop line by line and convert into array
$array[] = $line;
};
print_r($array); // display all value
echo $array[1]; // diplay index 1
Embed Online:
body, html, iframe { _x000D_
width: 100% ;_x000D_
height: 100% ;_x000D_
overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/vE1gst" ></iframe>
_x000D_
I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:
g.append('svg:text')
.attr('x', 0)
.attr('y', 30)
.attr('class', 'id')
.append('svg:tspan')
.attr('x', 0)
.attr('dy', 5)
.text(function(d) { return d.name; })
.append('svg:tspan')
.attr('x', 0)
.attr('dy', 20)
.text(function(d) { return d.sname; })
.append('svg:tspan')
.attr('x', 0)
.attr('dy', 20)
.text(function(d) { return d.idcode; })
There are 3 lines separated with linebreak.
Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.
This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.
For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:
Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543
Your Outlook recipient will see the information all smashed together, as follows:
Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543
There doesn't seem to be an easy solution. Alternatives are:
You should try detect the first line.
Then the:
if(n == 0){
line = words[n]+"\n";
}
I'm not sure, but maybe it helps.
On Linux and Mac OS, the following works,
:%s/^V^M/^V^M/g
where ^V^M
means type Ctrl+V, then Ctrl+M.
Note: on Windows you probably want to use ^Q
instead of ^V
, since by default ^V
is mapped to paste text.
You can view break lines using gedit editor.
First, if you don't have installed:
sudo apt-get install gedit
Now, install gedit plugins:
sudo apt-get install gedit-plugins
and select Draw Spaces plugin, enter on Preferences, and chose Draw new lines
Using VSCode you can install Line endings extension.
Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type
shift + ctrl + p
and start type the name of the plugin, and toggle to show line ending.
As Html.fromHtml
deprecated I simply I used this code to get String2 in next line.
textView.setText(fromHtml("String1 <br/> String2"));
.
@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
Simply use hr tag in HTML file and add below code in CSS file .
hr {
display: block;
position: relative;
padding: 0;
margin: 8px auto;
height: 0;
width: 100%;
max-height: 0;
font-size: 1px;
line-height: 0;
clear: both;
border: none;
border-top: 1px solid #aaaaaa;
border-bottom: 1px solid #ffffff;
}
it works perfectly .
You can just use
1: alert("Please select file" +
2: " to delete");
That should work
old question but this is a pretty neat and clean fix, might come in use for people who are still wondering if it's possible :):
br{_x000D_
content: '.';_x000D_
display: inline-block;_x000D_
width: 100%;_x000D_
border-bottom: 1px dashed black;_x000D_
}
_x000D_
with this fix you can also remove BRs on websites ( just set the width to 0px )
All three way you can use for newline character :
'\n'
"\n"
"""\n"""
DB related code looks easier on the eyes in multiple lines, enclosed by a pair of triple quotes:
SQL = """SELECT
id,
fld_1,
fld_2,
fld_3,
......
FROM some_tbl"""
than the following one giant long line:
SQL = "SELECT id, fld_1, fld_2, fld_3, .................................... FROM some_tbl"
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
This worked for me:
foreach (var item in FirmNameList){
if (FirmNames != "")
{
FirmNames += ",\r\n"
}
FirmNames += item;
}
string myText =
@"<div class=""firstLine""></div>
<div class=""secondLine""></div>
<div class=""thirdLine""></div>";
that's not it:
string myText =
@"<div class=\"firstLine\"></div>
<div class=\"secondLine\"></div>
<div class=\"thirdLine\"></div>";
Found that using the following worked across most major browsers (Chrome, IE, Safari iOS/OSX) except Firefox (v50.0.2) when using flexbox and relying on width: auto
.
.your_element {
word-wrap: break-word;
overflow-wrap: break-word;
word-break: break-word;
}
Note: you may need to add browser vendor prefixes if you are not using an autoprefixer.
Another thing to watch out for is text using
for spacing can cause line breaks mid-word.
You can't target each word in CSS. However, with a bit of jQuery you probably could.
With jQuery you can wrap each word in a <span>
and then CSS set span to display:block
which would put it on its own line.
In theory of course :P
Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.
Example:<br />
$myoutput = "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput = str_replace(".|..","<br />",$myoutput);<br />
or
how about:<br />
$myoutput = "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput = str_replace("E(*)3","<br />",$myoutput);<br />
I call the first method "middle finger style" and the second "goatse style".
print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")
\n - simple newline character insertion works:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
# Output:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
You might want to use \n
instead of /n
.
temp = open(filename,'r').read().splitlines()
You could use str_replace
to replace the <br />
tags into end of line characters.
str_replace('<br />', PHP_EOL, $textarea);
Alternatively, you could save the data in the database without calling nl2br
first. That way the line breaks would remain. When you display as HTML, call nl2br
. An additional benefit of this approach is that it would require less storage space in your database as a line break is 1 character as opposed to "<br />
" which is 6.
Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character ⁠ on either side of your hyphen, or em dash, or any character.
So, like so:
⁠—⁠
This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.
Reading perlport I'd suggest something like
$line =~ s/\015?\012?$//;
to be safe for whatever platform you're on and whatever linefeed style you may be processing because what's in \r and \n may differ through different Perl flavours.
If you want to remove only the last newline, pipe through:
sed -z '$ s/\n$//'
sed
won't add a \0
to then end of the stream if the delimiter is set to NUL
via -z
, whereas to create a POSIX text file (defined to end in a \n
), it will always output a final \n
without -z
.
Eg:
$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender
And to prove no NUL
added:
$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72 foo.bar
To remove multiple trailing newlines, pipe through:
sed -Ez '$ s/\n+$//'
CR - ASCII code 13
LF - ASCII code 10.
Theoretically CR returns cursor to the first position (on the left). LF feeds one line moving cursor one line down. This is how in old days you controled printers and text-mode monitors. These characters are usually used to mark end of lines in text files. Different operating systems used different conventions. As you pointed out Windows uses CR/LF combination while pre-OSX Macs use just CR and so on.
Try this:
echo str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $description);
Uses Guava's static factory methods for Maps and is only 105 characters long.
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper = Maps.newHashMap();
From the horse's mouth: Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (
\
), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
I have a textarea with id is #infoartist follow:
<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>
In javascript code, i'll get value of textarea and replace escaping new line (\n\r) by <br />
tag, such as:
var text = document.getElementById("infoartist").value;
text = text.replace(/\r?\n/g, '<br />');
So if you are using jquery (like me):
var text = $("#infoartist").val();
text = text.replace(/\r?\n/g, '<br />');
Hope it helped you. :-)
There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"]; echo nl2br($text);
Another situation is to check that the Primary Key is the same name as with your classes where the only difference is that your primary key has an 'ID' appended to it or to specify [Key] on primary keys that are not related to how the class is named.
I'd like to post some important information about undefined
, which beginners might not know.
Look at the following code:
/*
* Consider there is no code above.
* The browser runs these lines only.
*/
// var a;
// --- commented out to point that we've forgotten to declare `a` variable
if ( a === undefined ) {
alert('Not defined');
} else {
alert('Defined: ' + a);
}
alert('Doing important job below');
If you run this code, where variable a
HAS NEVER BEEN DECLARED using var
,
you will get an ERROR EXCEPTION and surprisingly see no alerts at all.
Instead of 'Doing important job below', your script will TERMINATE UNEXPECTEDLY, throwing unhandled exception on the very first line.
Here is the only bulletproof way to check for undefined
using typeof
keyword, which was designed just for such purpose:
/*
* Correct and safe way of checking for `undefined`:
*/
if ( typeof a === 'undefined' ) {
alert(
'The variable is not declared in this scope, \n' +
'or you are pointing to unexisting property, \n' +
'or no value has been set yet to the variable, \n' +
'or the value set was `undefined`. \n' +
'(two last cases are equivalent, don\'t worry if it blows out your mind.'
);
}
/*
* Use `typeof` for checking things like that
*/
This method works in all possible cases.
The last argument to use it is that undefined
can be potentially overwritten in earlier versions of Javascript:
/* @ Trollface @ */
undefined = 2;
/* Happy debuging! */
Hope I was clear enough.
I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.
using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
while (reader.Read()) {
// first element is the root element
if (reader.NodeType == XmlNodeType.Element) {
System.Console.WriteLine(reader.Name);
break;
}
}
}
this code perfectly run in my project
downloadImagesToSdCard(imagepath,imagepath);
private void downloadImagesToSdCard(String downloadUrl,String imageName)
{
try
{
URL url = new URL("www.xxx.com"+downloadUrl);
/* making a directory in sdcard */
// String sdCard=Environment.getExternalStorageDirectory().toString();
ContextWrapper cw = new ContextWrapper(getActivity());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("files", Context.MODE_PRIVATE);
File myDir = new File(directory,"folder");
/* if specified not exist create new */
if(!myDir.exists())
{
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File (myDir, fname);
Log.d("file===========path", ""+file);
if (file.exists ())
file.delete ();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection)ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
inputStream = httpConn.getInputStream();
/*if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
inputStream = httpConn.getInputStream();
}*/
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) >0 )
{
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
viewimage();
}
catch(IOException io)
{
io.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void viewimage()
{
String path = serialnumber+".png";
ContextWrapper cw = new ContextWrapper(getActivity());
//path to /data/data/yourapp/app_data/dirName
File directory = cw.getDir("files", Context.MODE_PRIVATE);
File mypath=new File(directory,"folder/"+path);
Bitmap b;
try {
b = BitmapFactory.decodeStream(new FileInputStream(mypath));
// b.compress(format, quality, stream)
profile_image.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
​
is the HTML entity for a unicode character called the zero-width space (ZWSP) which is an invisible character which specifies a line-break opportunity. Similarly the hyphen's purpose is to specify a line-break opportunity within a word boundary.
By using display: inline-block; And more generally when you have a parent (always there is a parent except for html) use display: inline-block;
for the inner elements. and to force them to stay in the same line even when the window get shrunk (contracted). Add for the parent the two property:
white-space: nowrap;
overflow-x: auto;
here a more formatted example to make it clear:
.parent {
white-space: nowrap;
overflow-x: auto;
}
.children {
display: inline-block;
margin-left: 20px;
}
For this example particularly, you can apply the above as fellow (i'm supposing the parent is body. if not you put the right parent), you can also like change the html and add a parent for them if it's possible.
body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
white-space: nowrap;
overflow-x: auto;
}
#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
display: inline-block;
margin-left: 10px;
}
keep in mind that white-space: nowrap;
and overlow-x: auto;
is what you need to force them to be in one line. white-space: nowrap; disable wrapping. And overlow-x:auto; to activate scrolling, when the element get over the frame limit.
All of the replies with readonly
are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.
Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.
There are several ways to manage this, but the pure TS way is to use a getter
- exactly as you have done already.
The alternative way is to put it in as readonly
, but then use Object.defineProperty
to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -
class MyClass {
MY_CONSTANT = 10;
constructor() {
Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
}
}
The defaults make it read-only, but check out the docs for more details.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
You could make use of expect (man expect comes with examples).
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method:
Found a solution that works for me looking here (see the third comment on the first answer). This code looks for a valid twitter client and uses it to post the tweet. Note: It does not give you an Intent with the various Twitter clients and allow you to choose.
Share using twitter:
Intent shareIntent = findTwitterClient();
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
startActivity(Intent.createChooser(shareIntent, "Share"));
Calling this method:
public Intent findTwitterClient() {
final String[] twitterApps = {
// package // name - nb installs (thousands)
"com.twitter.android", // official - 10 000
"com.twidroid", // twidroid - 5 000
"com.handmark.tweetcaster", // Tweecaster - 5 000
"com.thedeck.android" }; // TweetDeck - 5 000 };
Intent tweetIntent = new Intent();
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(
tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (int i = 0; i < twitterApps.length; i++) {
for (ResolveInfo resolveInfo : list) {
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i])) {
tweetIntent.setPackage(p);
return tweetIntent;
}
}
}
return null;
}
Facebook will be similar using "com.facebook.katana", although you still can't set the message text (deprecated July 2011).
Code source: Intent to open twitter client on Android
I came up with the same problem and I'm sharing how I fixed it. It may help some people.
First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :
**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**
<application ...>
...
</application>
Then, request that the user approve each permission at runtime
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// here, Permission is not granted
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
}
For more information, have a look at the API documentation here
You can use parents
method with specified .class
selector and check if any of them matches it:
if ($elem.parents('.left').length != 0) {
//someone has this class
}
I think the easiest way to make it done is :
std::vector<std::vector<int>>v(10,std::vector<int>(11,100));
10 is the size of the outer or global vector, which is the main one, and 11 is the size of inner vector of type int, and initial values are initialized to 100! That's my first help on stack, i think it helps someone.
In our case, the reason was invalid header. As mentioned in Edit 4:
Look for something similar:
HTTP2_SESSION_RECV_INVALID_HEADER
--> error = "Invalid character in header name."
--> header_name = "charset=utf-8"
If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :
FDOPEN(P)
NAME
fdopen - associate a stream with a file descriptor
SYNOPSIS
#include <stdio.h>
FILE *fdopen(int fildes, const char *mode);
You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to
DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.
Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.
Try This:
table.table tr th{background-color:blue !important; font-color:white !important;}
hope this helps..
switch ($value)
{
case 1:
case 2:
echo 'the value is either 1 or 2';
break;
}
Whenever such an error occurs. Try to check Following Things
Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.
Check if your activity type which is extended falls under the compat category
example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based
if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()
example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work
but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()
Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following
double (*A)[n] = malloc(sizeof(double[n][n]));
and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]
. And don't forget that one at the end
free(A);
Randy Meyers wrote series of articles explaining variable length arrays (VLAs).
If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.
I am beginning Angular and in my case, the issue was that I hadn't saved the file after adding the 'import' statement.
I selected None from Team dropdown in target general settings. Then selected the original team. Xcode shows some spinner next to it. Wait for it to complete and then everything works. Tried it in Xcode 6.2
this is an another way:
<html>
<head>
<title>Echo</title>
<style type="text/css">
#result{
border: 1px solid #000000;
min-height: 250px;
max-height: 100%;
padding: 5px;
font-family: sans-serif;
font-size: 12px;
}
</style>
<script type="text/javascript" lang="ja">
function start(){
function echo(text){
lastResultAreaText = document.getElementById('result').innerHTML;
resultArea = document.getElementById('result');
if(lastResultAreaText==""){
resultArea.innerHTML=text;
}
else{
resultArea.innerHTML=lastResultAreaText+"</br>"+text;
}
}
echo("Hello World!");
}
</script>
</head>
<body onload="start()">
<pre id="result"></pre>
</body>
Is it useful to look beyond the exact question asked to alternatives that might better suit the need? Create your own class or struct, then make an array of those to operate on instead of being stuck with the operation of the KeyValuePair collection behavior of the Dictionary type.
Using a struct instead of a class will allow equality comparison of two different cards without implementing your own comparison code.
public struct Card
{
public string Name;
public int Value;
}
private int random()
{
// Whatever
return 1;
}
private static Card[] Cards = new Card[]
{
new Card() { Name = "7", Value = 7 },
new Card() { Name = "8", Value = 8 },
new Card() { Name = "9", Value = 9 },
new Card() { Name = "10", Value = 10 },
new Card() { Name = "J", Value = 1 },
new Card() { Name = "Q", Value = 1 },
new Card() { Name = "K", Value = 1 },
new Card() { Name = "A", Value = 1 }
};
private void CardDemo()
{
int value, maxVal;
string name;
Card card, card2;
List<Card> lowCards;
value = Cards[random()].Value;
name = Cards[random()].Name;
card = Cards[random()];
card2 = Cards[1];
// card.Equals(card2) returns true
lowCards = Cards.Where(x => x.Value == 1).ToList();
maxVal = Cards.Max(x => x.Value);
}
In SQL Server you can turn on and off identity insert like this:
SET IDENTITY_INSERT table_name ON
-- run your queries here
SET IDENTITY_INSERT table_name OFF
I am surprised that nobody has mentioned that properties are bound methods of a descriptor class, Adam Donohue and NeilenMarais get at exactly this idea in their posts -- that getters and setters are functions and can be used to:
This presents a smart way to hide implementation details and code cruft like regular expression, type casts, try .. except blocks, assertions or computed values.
In general doing CRUD on an object may often be fairly mundane but consider the example of data that will be persisted to a relational database. ORM's can hide implementation details of particular SQL vernaculars in the methods bound to fget, fset, fdel defined in a property class that will manage the awful if .. elif .. else ladders that are so ugly in OO code -- exposing the simple and elegant self.variable = something
and obviate the details for the developer using the ORM.
If one thinks of properties only as some dreary vestige of a Bondage and Discipline language (i.e. Java) they are missing the point of descriptors.
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
This is a pithy solution.
import datetime
todayDate = datetime.date.today()
if todayDate.day > 25:
todayDate += datetime.timedelta(7)
print todayDate.replace(day=1)
One thing to note with the original code example is that using timedelta(30)
will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.
Sorry, but I'm pretty sure Peter's answer is wrong. Note that the y axis goes down the page (common in graphics). As such the deltaY calculation has to be reversed, or you get the wrong answer.
Consider:
System.out.println (Math.toDegrees(Math.atan2(1,1)));
System.out.println (Math.toDegrees(Math.atan2(-1,1)));
System.out.println (Math.toDegrees(Math.atan2(1,-1)));
System.out.println (Math.toDegrees(Math.atan2(-1,-1)));
gives
45.0
-45.0
135.0
-135.0
So if in the example above, P1 is (1,1) and P2 is (2,2) [because Y increases down the page], the code above will give 45.0 degrees for the example shown, which is wrong. Change the order of the deltaY calculation and it works properly.
I see 4 issues with your code:
setState
method to actually change the stateLet's try to fix that:
componentDidMount: function() {
var intervalId = setInterval(this.timer, 1000);
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: intervalId});
},
componentWillUnmount: function() {
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
},
timer: function() {
// setState method is used to update the state
this.setState({ currentCount: this.state.currentCount -1 });
},
render: function() {
// You do not need to decrease the value here
return (
<section>
{this.state.currentCount}
</section>
);
}
This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:
timer: function() {
var newCount = this.state.currentCount - 1;
if(newCount >= 0) {
this.setState({ currentCount: newCount });
} else {
clearInterval(this.state.intervalId);
}
},
Here is working solution!!!
@SuppressWarnings("unchecked")
private Class<T> getGenericTypeClass() {
try {
String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
Class<?> clazz = Class.forName(className);
return (Class<T>) clazz;
} catch (Exception e) {
throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
}
}
NOTES:
Can be used only as superclass
1. Has to be extended with typed class (Child extends Generic<Integer>
)
OR
2. Has to be created as anonymous implementation (new Generic<Integer>() {};
)
You can use methodsolver
to find Ruby functions.
Here is a small script,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
Running this prints
Found 1 methods
- Array#unshift
You can install methodsolver using
gem install methodsolver
You can use the nth-child
CSS selector to hide a whole column:
#myTable tr > *:nth-child(2) {
display: none;
}
This works under assumption that a cell of column N (be it a th
or td
) is always the Nth child element of its row.
?
If you want the column number to be dynamic, you could do that using querySelectorAll
or any framework presenting similar functionality, like jQuery
here:
$('#myTable tr > *:nth-child(2)').hide();
(The jQuery solution also works on legacy browsers that don't support nth-child
).
Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.
Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.
One thing to consider might be a "ForTest" suffix:
internal void DoThisForTest(string name)
{
DoThis(name);
}
private void DoThis(string name)
{
// Real implementation
}
Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.
With following script you can save movie to Videos folder
Example usage:
download-video.sh https://url.com/video.mp4 video-name
download-video.sh
#!/bin/bash
LINK=$1
NAME=$2
START=0
END=2000
help()
{
echo "download-video.sh <url> <output-name>"
echo "<url>: x.mp4 (without .ts)"
echo "<output-name>: x (without .mp4)"
}
create_folders()
{
# create folder for streaming media
cd ~/Videos
mkdir download-videos
cd download-videos
}
print_variables()
{
echo "Execute Download with following parameters"
echo "Link $LINK"
echo "Name $NAME"
}
check_video()
{
i=$START
while [[ $i -le $END ]]
do
URL=$LINK'-'$i.ts
STATUS_CODE=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $URL)
if [ "$STATUS_CODE" == "200" ]; then
break
fi
((i = i + 1))
done
if [ "$STATUS_CODE" == "200" ]; then
START=$i
echo "START is $START"
else
echo "File not found"
fi
}
download_video()
{
i=$START
e=$END
while [[ $i -le $END ]]
do
URL=$LINK'-'$i.ts
STATUS_CODE=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $URL)
if [ "$STATUS_CODE" != "200" ]; then
break
fi
wget $URL
e=$i
((i = i + 1))
done
END=$e
}
concat_videos()
{
DIR="${LINK##*/}"
i=$START
echo "i is $i"
while [[ $i -le $END ]]
do
FILE=$DIR'-'$i.ts
echo $FILE | tr " " "\n" >> tslist
((i = i + 1))
done
while read line;
do
echo "gugu"$line
cat $line >> $NAME.mp4;
done < tslist
rm *.ts tslist
}
if [ "$1" == "" ]; then
echo "No video url provided"
help
else
LINK=$1
if [ "$2" == "" ]; then
echo "No video output-name provided"
help
else
NAME=$2
create_folders
print_variables
check_video
download_video
concat_videos
fi
fi
Run in command prompt.
pip list
Check what version you have installed on your system if you have an old version.
Try to uninstall the package...
pip uninstall requests
Try after to install it:
pip install requests
You can also test if pip does not do the job.
easy_install requests
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/
I had the same issue on linux, but I couldn't fix it with the accepted answer. I was able to solve it by using cd
to go to the correct folder and then executing:
svn remove --force filename
syn resolve --accept=working filename
svn up
That's all.
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
The best solution is using a static site generator which has templating/includes support. I use Hammer for Mac, it is great. There's also Guard, a ruby gem that monitors file changes, compile sass, concatenate any files and probably does includes.
There is a better way!
To make the VStack
fill the width of it's parent you can use a GeometryReader
and set the frame. (.relativeWidth(1.0)
should work but apparently doesn't right now)
struct ContentView : View {
var body: some View {
GeometryReader { geometry in
VStack {
Text("test")
}
.frame(width: geometry.size.width,
height: nil,
alignment: .topLeading)
}
}
}
To make the VStack
the width of the actual screen you can use UIScreen.main.bounds.width
when setting the frame instead of using a GeometryReader
, but I imagine you likely wanted the width of the parent view.
Also, this way has the added benefit of not adding spacing in your VStack
which might happen (if you have spacing) if you added an HStack
with a Spacer()
as it's content to the VStack
.
UPDATE - THERE IS NOT A BETTER WAY!
After checking out the accepted answer, I realized that the accepted answer doesn't actually work! It appears to work at first glance, but if you update the VStack
to have a green background you'll notice the VStack
is still the same width.
struct ContentView : View {
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Text("Hello World")
.font(.title)
Text("Another")
.font(.body)
Spacer()
}
.background(Color.green)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
.background(Color.red)
}
}
}
This is because .frame(...)
is actually adding another view to the view hierarchy and that view ends up filling the screen. However, the VStack
still does not.
This issue also seems to be the same in my answer as well and can be checked using the same approach as above (putting different background colors before and after the .frame(...)
. The only way that appears to actually widen the VStack
is to use spacers:
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
HStack{
Text("Title")
.font(.title)
Spacer()
}
Text("Content")
.lineLimit(nil)
.font(.body)
Spacer()
}
.background(Color.green)
}
}
Or you can use what JQuery alreay made for you:
http://jqueryui.com/datepicker/#icon-trigger
It's what you are trying to achieve isn't it?
Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly
There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.
It seems that it does not matter what timezone is on the server as long as you have the time set right for the current timezone, know the timezone of the datetime columns that you store, and are aware of the issues with daylight savings time.
On the other hand if you have control of the timezones of the servers you work with then you can have everything set to UTC internally and never worry about timezones and DST.
Here are some notes I collected of how to work with timezones as a form of cheatsheet for myself and others which might influence what timezone the person will choose for his/her server and how he/she will store date and time.
Notes:
GMT confuses seconds, which is why UTC was invented.
Warning! different regional timezones might produce the same datetime value due to daylight savings time
Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.
When storing a date in a timestamp, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.
no matter what timezone the current MySQL session is in:
SELECT
CONVERT_TZ(`timestamp_field`, @@session.time_zone, '+00:00') AS `utc_datetime`
FROM `table_name`
You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:
SELECT `timestamp_field` FROM `table_name`
SELECT UTC_TIMESTAMP();
SELECT UTC_TIMESTAMP;
SELECT CONVERT_TZ(NOW(), @@session.time_zone, '+00:00');
Example result: 2015-03-24 17:02:41
SELECT NOW();
SELECT CURRENT_TIMESTAMP;
SELECT CURRENT_TIMESTAMP();
SELECT @@system_time_zone;
Returns "MSK" or "+04:00" for Moscow time for example, there is (or was) a MySQL bug where if set to a numerical offset it would not adjust the Daylight savings time
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return 02:00:00 if your timezone is +2:00.
SELECT UNIX_TIMESTAMP(NOW());
SELECT UNIX_TIMESTAMP();
SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`
SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`
SELECT FROM_UNIXTIME(`unix_timestamp_int`) FROM `table_name`
SELECT CONVERT_TZ(FROM_UNIXTIME(`unix_timestamp_int`), @@session.time_zone, '+00:00')
FROM `table_name`
SELECT DATE_ADD('1970-01-01 00:00:00',INTERVAL -957632400 SECOND)
Note: A timezone can be set in 2 formats:
Named time zones can be used only if the time zone information tables in the mysql database have been created and populated.
default_time_zone='+00:00'
or
timezone='UTC'
To see what value they are set to
SELECT @@global.time_zone;
To set a value for it use either one:
SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';
SELECT @@session.time_zone;
To set it use either one:
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";
both "@@global.time_zone variable" and "@@session.time_zone variable" might return "SYSTEM" which means that they use the timezone set in "my.cnf".
For timezone names to work (even for default-time-zone) you must setup your timezone information tables need to be populated: http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html
Note: you can not do this as it will return NULL:
SELECT
CONVERT_TZ(`timestamp_field`, TIMEDIFF(NOW(), UTC_TIMESTAMP), '+00:00') AS `utc_datetime`
FROM `table_name`
For CONVERT_TZ
to work, you need the timezone tables to be populated
SELECT * FROM mysql.`time_zone` ;
SELECT * FROM mysql.`time_zone_leap_second` ;
SELECT * FROM mysql.`time_zone_name` ;
SELECT * FROM mysql.`time_zone_transition` ;
SELECT * FROM mysql.`time_zone_transition_type` ;
If they are empty, then fill them up by running this command
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
if this command gives you the error "data too long for column 'abbreviation' at row 1", then it might be caused by a NULL character being appended at the end of the timezone abbreviation
the fix being to run this
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
(if the above gives error "data too long for column 'abbreviation' at row 1")
mysql_tzinfo_to_sql /usr/share/zoneinfo > /tmp/zut.sql
echo "SET SESSION SQL_MODE = '';" > /tmp/mysql_tzinfo_to.sql
cat /tmp/zut.sql >> /tmp/mysql_tzinfo_to.sql
mysql --defaults-file=/etc/mysql/my.cnf --user=verifiedscratch -p mysql < /tmp/mysql_tzinfo_to.sql
(make sure your servers dst rules are up to date zdump -v Europe/Moscow | grep 2011
https://chrisjean.com/updating-daylight-saving-time-on-linux/)
SELECT
tzn.Name AS tz_name,
tztt.Abbreviation AS tz_abbr,
tztt.Is_DST AS is_dst,
tztt.`Offset` AS `offset`,
DATE_ADD('1970-01-01 00:00:00',INTERVAL tzt.Transition_time SECOND) AS transition_date
FROM mysql.`time_zone_transition` tzt
INNER JOIN mysql.`time_zone_transition_type` tztt USING(Time_zone_id, Transition_type_id)
INNER JOIN mysql.`time_zone_name` tzn USING(Time_zone_id)
-- WHERE tzn.Name LIKE 'Europe/Moscow' -- Moscow has weird DST changes
ORDER BY tzt.Transition_time ASC
CONVERT_TZ
also applies any necessary DST changes based on the rules in the above tables and the date that you use.
Note:
According to the docs, the value you set for time_zone does not change, if you set it as "+01:00" for example, then the time_zone will be set as an offset from UTC, which does not follow DST, so it will stay the same all year round.
Only the named timezones will change time during daylight savings time.
Abbreviations like CET
will always be a winter time and CEST
will be summer time while +01:00 will always be UTC
time + 1 hour and both won't change with DST.
The system
timezone will be the timezone of the host machine where mysql is installed (unless mysql fails to determine it)
You can read more about working with DST here
related questions:
Sources:
I had a simular need. Here is what I did:
<script type="text/javascript" language="javascript">
function convertEnterToTab() {
if(event.keyCode==13) {
event.keyCode = 9;
}
}
document.onkeydown = convertEnterToTab;
</script>
You can
declare var require: any
Or, for more comprehensive support, use DefinitelyTyped's require.d.ts
Also, instead of var mongoose = require('mongoose')
, you could try the following
import mongoose from 'mongoose' // or
import mongoose = require('mongoose')
cat ip_addresses | sort | uniq -c | sort -nr | awk '{print $2 " " $1}'
this command would give you desired output
Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.
I have had the same problem. And it was hard to find. But somewhere in my code was this:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return nil;
}
It must be return indexPath
, else -tableView:didSelectRowAtIndexPath:
is not being called.
Add the below declarations to your class:
public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
After:
var client = new HttpClient();
And:
ServicePointManager.SecurityProtocol = Tls12;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 /*| SecurityProtocolType.Tls */| Tls12;
Happy? :)
Go to your project's "Properties" within visual studio. Then go to signing tab.
Then make sure Sign the Click Once manifests is turned off.
Updated Instructions:
Within your Solution Explorer:
Another method is to define an exception and then only catch that exception letting all others propagate.
Declare
eTableDoesNotExist Exception;
PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
Begin
EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
Exception
When eTableDoesNotExist Then
DBMS_Output.Put_Line('Table already does not exist.');
End;
It will post a log message to the browser's javascript console, e.g. Firebug or Developer Tools (Chrome / Safari) and will show the line and file where it was executed from.
Moreover, when you output a jQuery Object it will include a reference to that element in the DOM, and clicking it will go to that in the Elements/HTML tab.
You can use various methods, but beware that for it to work in Firefox, you must have Firebug open, otherwise the whole page will crash. Whether what you're logging is a variable, array, object or DOM element, it will give you a full breakdown including the prototype for the object as well (always interesting to have a poke around). You can also include as many arguments as you want, and they will be replaced by spaces.
console.log( myvar, "Logged!");
console.info( myvar, "Logged!");
console.warn( myvar, "Logged!");
console.debug(myvar, "Logged!");
console.error(myvar, "Logged!");
These show up with different logos for each command.
You can also use console.profile(profileName);
to start profiling a function, script etc. And then end it with console.profileEnd(profileName);
and it will show up in you Profiles tab in Chrome (don't know with FF).
For a complete reference go to http://getfirebug.com/logging and I suggest you read it. (Traces, groups, profiling, object inspection).
Hope this helps!
Coded an example at http://jsbin.com/orisuv
HTML
<select name="color" onchange='checkvalue(this.value)'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color" style='display:none'/>
Javascript
function checkvalue(val)
{
if(val==="others")
document.getElementById('color').style.display='block';
else
document.getElementById('color').style.display='none';
}
here is the sample code to draw image on canvas-
$("#selectedImage").change(function(e) {
var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 500, 500);
}});
In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
For completeness' sake, I'd like to point out that sometimes you may want to parse code instead of importing it. An import
will execute top-level expressions, and that could be a problem.
For example, I'm letting users select entry point functions for packages being made with zipapp. Using import
and inspect
risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.
Instead I use the ast module to list all the top-level functions:
import ast
import sys
def top_level_functions(body):
return (f for f in body if isinstance(f, ast.FunctionDef))
def parse_ast(filename):
with open(filename, "rt") as file:
return ast.parse(file.read(), filename=filename)
if __name__ == "__main__":
for filename in sys.argv[1:]:
print(filename)
tree = parse_ast(filename)
for func in top_level_functions(tree.body):
print(" %s" % func.name)
Putting this code in list.py
and using itself as input, I get:
$ python list.py list.py
list.py
top_level_functions
parse_ast
Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.
Though, a downside is that you can't detect functions that are generated at runtime, like foo = lambda x,y: x*y
.
To see which ports are available on your machine run:
C:> netstat -an |find /i "listening"
For Excel POI:
sheetName.autoSizeColumn(cellnum);
I have used the gem CodeRay and it works pretty well. The format includes colors and it recognises a lot of different formats.
I have used it on a gem that can be used for debugging rails APIs and it works pretty well.
By the way, the gem is named 'api_explorer' (http://www.github.com/toptierlabs/api_explorer)
From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:
<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>
You cannot effectively hide your HTML and JavaScript code, even if you encrypt or minify it.
If the code you're trying to hide is really sensitive, it should either be in a protected area of the site, i.e. an area that you can only access via a username and password, or potentially in a client application that isn't exposed via the web.
If you have to expose the application functionality via a web frontend, you could use Silverlight to write the frontend or bits of the frontend. In the old days you could also use ActiveX.
Apparently, org.json.simple.JSONArray
implements a raw Iterator. This means that each element is considered to be an Object
. You can try to cast:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.
Depends on where the file you are trying to include from is located.
Example:
/rootdir/pages/file.php
/someotherDir/index.php
If you wrote the following in index.php:
include('/rootdir/pages/file.php');
it would error becuase it would try to get:
/someotherDir/rootdir/pages/file.php
Which of course doesn't exist...
So you would have to use include('../rootdir/pages/file.php');
if you just run the main.py
under the app
, just import like
from mymodule import myclass
if you want to call main.py
on other folder, use:
from .mymodule import myclass
for example:
+-- app
¦ +-- __init__.py
¦ +-- main.py
¦ +-- mymodule.py
+-- __init__.py
+-- run.py
main.py
from .mymodule import myclass
run.py
from app import main
print(main.myclass)
So I think the main question of you is how to call app.main
.
This one I found simple solutions:
row = myArray.map((cell, i) => {
if (i == myArray.length - 1) {
return <div> Test Data 1</div>;
}
return <div> Test Data 2</div>;
});
The difference between memcpy
and memmove
is that
in memmove
, the source memory of specified size is copied into buffer and then moved to destination. So if the memory is overlapping, there are no side effects.
in case of memcpy()
, there is no extra buffer taken for source memory. The copying is done directly on the memory so that when there is memory overlap, we get unexpected results.
These can be observed by the following code:
//include string.h, stdio.h, stdlib.h
int main(){
char a[]="hare rama hare rama";
char b[]="hare rama hare rama";
memmove(a+5,a,20);
puts(a);
memcpy(b+5,b,20);
puts(b);
}
Output is:
hare hare rama hare rama
hare hare hare hare hare hare rama hare rama
If your'e using Web Forms then Grid View can work very nicely for this
The code looks a little like this.
aspx page.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>
You can either input the data manually or use the source method in the code side
public class Room
{
public string Name
public double Size {get; set;}
public int Quantity {get; set;}
public double Amount {get; set;}
public int Duration {get; set;}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)//this is so you can keep any data you want for the list
{
List<Room> rooms=new List<Room>();
//then use the rooms.Add() to add the rooms you need.
GridView1.DataSource=rooms
GridView1.Databind()
}
}
Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.
The View would look like this.
@model YourProject.Model.IEnumerable<Room>
<table>
<th>
<td>@Html.LabelFor(model => model.Name)</td>
<td>@Html.LabelFor(model => model.Size)</td>
<td>@Html.LabelFor(model => model.Quantity)</td>
<td>@Html.LabelFor(model => model.Amount)</td>
<td>@Html.LabelFor(model => model.Duration)</td>
</th>
foreach(item in model)
{
<tr>
<td>@model.Name</td>
<td>@model.Size</td>
<td>@model.Quantity</td>
<td>@model.Amount</td>
<td>@model.Duration</td>
</tr>
}
</table>
The controller might look something like this.
public ActionResult Index()
{
List<Room> rooms=new List<Room>();
//again add the items you need
return View(rooms);
}
Hope this helps :)
If you do have a legitimate need to run some js
from a partial
, here's how you could do it, jQuery
is required:
<script type="text/javascript">
function scriptToExecute()
{
//The script you want to execute when page is ready.
}
function runWhenReady()
{
if (window.$)
scriptToExecute();
else
setTimeout(runWhenReady, 100);
}
runWhenReady();
</script>
This is an example for a RelativeLayout:
RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeLayout.setLayoutParams(params);
With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.
All the answers here use JSON objects. This gave us problems with the
$this->input->post()
methods of our Codeigniter controllers. The CI_Controller
cannot read JSON directly.
We used this method to do it WITHOUT JSON
func postRequest() {
// Create url object
guard let url = URL(string: yourURL) else {return}
// Create the session object
let session = URLSession.shared
// Create the URLRequest object using the url object
var request = URLRequest(url: url)
// Set the request method. Important Do not set any other headers, like Content-Type
request.httpMethod = "POST" //set http method as POST
// Set parameters here. Replace with your own.
let postData = "param1_id=param1_value¶m2_id=param2_value".data(using: .utf8)
request.httpBody = postData
// Create a task using the session object, to run and return completion handler
let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
guard error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
guard let serverData = data else {
print("server data error")
return
}
do {
if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
print("Response: \(requestJson)")
}
} catch let responseError {
print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
let message = String(bytes: serverData, encoding: .ascii)
print(message as Any)
}
// Run the task
webTask.resume()
}
Now your CI_Controller will be able to get param1
and param2
using $this->input->post('param1')
and $this->input->post('param2')
Use this, I think I can get your idea.
Live demo: http://jsfiddle.net/oscarj24/h722g/1/
$('body').click(function(e) {
var target = $(e.target), article;
if (target.is('#news_gallery li .over')) {
article = $('#news-article .news-article');
} else if (target.is('#work_gallery li .over')) {
article = $('#work-article .work-article');
} else if (target.is('#search-item li')) {
article = $('#search-item .search-article');
}
if (article) {
// Do Something
}
});?
Beware that when the mounted
event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.
To really simulate the DOM onload
event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted
:
mounted: function () {
this.$nextTick(function () {
// Will be executed when the DOM is ready
})
}
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this
$ operator is invalid for atomic vectors
You can use [
in that case
foo[order(foo["V1"]),]
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
If you want to execute a local script remotely without saving that script remotely you can do it like this:
cat local_script.sh | ssh user@remotehost 'bash -'
It works like a charm for me.
I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.
Just try it like this:
<!-- A light one -->
<nav class="navbar navbar-default" role="navigation"></nav>
<!-- A dark one -->
<nav class="navbar navbar-inverse" role="navigation"></nav>
navabr.css
/* Navbar */
.navbar-default {
background-color: #F8F8F8;
border-color: #E7E7E7;
}
/* Title */
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5E5E5E;
}
/* Link */
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #E7E7E7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #D5D5D5;
}
/* Caret */
.navbar-default .navbar-nav > .dropdown > a .caret {
border-top-color: #777;
border-bottom-color: #777;
}
.navbar-default .navbar-nav > .dropdown > a:hover .caret,
.navbar-default .navbar-nav > .dropdown > a:focus .caret {
border-top-color: #333;
border-bottom-color: #333;
}
.navbar-default .navbar-nav > .open > a .caret,
.navbar-default .navbar-nav > .open > a:hover .caret,
.navbar-default .navbar-nav > .open > a:focus .caret {
border-top-color: #555;
border-bottom-color: #555;
}
/* Mobile version */
.navbar-default .navbar-toggle {
border-color: #DDD;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #DDD;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #CCC;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
}
}
The default major color uses are as below:
You can learn more in To change navbar color in Twitter Bootstrap 3.
Restarting the app will call OnCreate()
.
Continuing the app when it is paused will call OnResume()
. From the official docs at https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle here's a diagram of the activity lifecycle.
per various post... you cannot trigger a download via XHR. I needed to implement condition for the download, so, My solution was:
//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
//confirm that the ID is validated
if (data.isIdConfirmed) {
//get the token from the validation and issue another call
//to trigger the download
window.open('someapi/print/:someId?token='+ data.token);
}
});
I wish that somehow, or someday the download can be triggered using XHR to avoid the second call. // _e
Remove servlet.jar
from source web-inf/lib
folder as it is available in tomcat lib
folder then it works fine
I used attached behaviours to close the window. Bind a "signal" property on your ViewModel to the attached behaviour (I actually use a trigger) When it's set to true, the behaviour closes the window.
http://adammills.wordpress.com/2009/07/01/window-close-from-xaml/
This just happened to me.
Solution: Pull down my own branch so I get that extra commit. Then push it back to my remote branch.
literally what I did on my branch was:
git pull
git push
I would go with linking the second object into a property of the first object. If the second object is the result of a function or method, use references. Ex:
//Not the result of a method
$obj1->extra = new Class2();
//The result of a method, for instance a factory class
$obj1->extra =& Factory::getInstance('Class2');
In ASP.NET there is similar object, you can use Caching Portions in WebFormsUserControls in order to cache objects of a page for a period of time and save server resources. This is also known as fragment caching.
If you include this code to top of your user control, a version of the control stored in the output cache for 150 seconds.
You can create your own control that would contain expire header for a specific resource you want.
<%@ OutputCache Duration="150" VaryByParam="None" %>
This article explain it completely: Caching Portions of an ASP.NET Page
You could make a little Tkinter app:
import Tkinter as tk
def onKeyPress(event):
text.insert('end', 'You pressed %s\n' % (event.char, ))
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
This is the code I wound up with, based upon the other answers here. This is for an HttpPost that receives and responds with complex types:
Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(
strMyHttpPostURL,
new MyComplexObject { Param1 = param1, Param2 = param2}).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
//debug:
//String s = response.Result.Content.ReadAsStringAsync().Result;
MyOtherComplexType moct = (MyOtherComplexType)JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result, typeof(MyOtherComplexType));
You need to add target for that button.
myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)
FunctionName: connected // for example
And of course you need to set tag of that button since you are using it.
myButton.tag = indexPath.row
You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.
To get the tag in the connected function:
func connected(sender: UIButton) {
let buttonTag = sender.tag
// Do any additional setup
}
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
Addressing an element of dictionary is like sitting on donkey and enjoy the ride.
As a rule of Python, a DICTIONARY is orderless
If there is
dic = {1: "a", 2: "aa", 3: "aaa"}
Now suppose if I go like dic[10] = "b"
, then it will not add like this always
dic = {1:"a",2:"aa",3:"aaa",10:"b"}
It may be like
dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}
Or
dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}
Or
dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}
Or any such combination.
So a rule of thumb is that a DICTIONARY is orderless!
(Which isn't true, because it stands for Representational, but it's a good trick to remember the importance of Resources in REST).
About PUT /groups/api/v1/groups/{group id}/status/activate
: you are not updating an "activate". An "activate" is not a thing, it's a verb. Verbs are never good resources. A rule of thumb: if the action, a verb, is in the URL, it probably is not RESTful.
What are you doing instead? Either you are "adding", "removing" or "updating" an activation on a Group, or if you prefer: manipulating a "status"-resource on a Group. Personally, I'd use "activations" because they are less ambiguous than the concept "status": creating a status is ambiguous, creating an activation is not.
POST /groups/{group id}/activation
Creates (or requests the creation of) an activation.PATCH /groups/{group id}/activation
Updates some details of an existing activation. Since a group has only one activation, we know what activation-resource we are referring to.PUT /groups/{group id}/activation
Inserts-or-replaces the old activation. Since a group has only one activation, we know what activation-resource we are referring to.DELETE /groups/{group id}/activation
Will cancel, or remove the activation.This pattern is useful when the "activation" of a Group has side-effects, such as payments being made, mails being sent and so on. Only POST and PATCH may have such side-effects. When e.g. a deletion of an activation needs to, say, notify users over mail, DELETE is not the right choice; in that case you probably want to create a deactivation resource: POST /groups/{group_id}/deactivation
.
It is a good idea to follow these guidelines, because this standard contract makes it very clear for your clients, and all the proxies and layers between the client and you, know when it is safe to retry, and when not. Let's say the client is somewhere with flaky wifi, and its user clicks on "deactivate", which triggers a DELETE
: If that fails, the client can simply retry, until it gets a 404, 200 or anything else it can handle. But if it triggers a POST to deactivation
it knows not to retry: the POST implies this.
Any client now has a contract, which, when followed, will protect against sending out 42 emails "your group has been deactivated", simply because its HTTP-library kept retrying the call to the backend.
PATCH /groups/{group id}
In case you wish to update an attribute. E.g. the "status" could be an attribute on Groups that can be set. An attribute such as "status" is often a good candidate to limit to a whitelist of values. Examples use some undefined JSON-scheme:
PATCH /groups/{group id} { "attributes": { "status": "active" } }
response: 200 OK
PATCH /groups/{group id} { "attributes": { "status": "deleted" } }
response: 406 Not Acceptable
PUT /groups/{group id}
In case you wish to replace an entire Group. This does not necessarily mean that the server actually creates a new group and throws the old one out, e.g. the ids might remain the same. But for the clients, this is what PUT can mean: the client should assume he gets an entirely new item, based on the server's response.
The client should, in case of a PUT
request, always send the entire resource, having all the data that is needed to create a new item: usually the same data as a POST-create would require.
PUT /groups/{group id} { "attributes": { "status": "active" } }
response: 406 Not Acceptable
PUT /groups/{group id} { "attributes": { "name": .... etc. "status": "active" } }
response: 201 Created or 200 OK, depending on whether we made a new one.
A very important requirement is that PUT
is idempotent: if you require side-effects when updating a Group (or changing an activation), you should use PATCH
. So, when the update results in e.g. sending out a mail, don't use PUT
.
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
Firebug + console.log(myObjectInstance)
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
[class*="test"],[class="second"] {
background: #ffff00;
}
It's easy, if your mailx
command supports the -a
(append header) option:
$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html
If it doesn't, try using sendmail
:
# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html
# send
$ cat mailheader email.html | sendmail -t
The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).
You need to actually include the header (using a #include
directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.
It's a table-valued function, but you're using it as a scalar function.
Try:
where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)
But... also consider changing your function into an inline TVF, as it'll perform better.
This feature was added to the 1.1.5 release via a timeout parameter:
var canceler = $q.defer();
$http.get('/someUrl', {timeout: canceler.promise}).success(successCallback);
// later...
canceler.resolve(); // Aborts the $http request if it isn't finished.
Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:
body {
-webkit-font-smoothing: antialiased;
text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
background: url('./images/background.png');
text-align: left;
margin: auto;
}
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).
The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.
It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.
If it isn't already there, create an .htaccess file in the Laravel root directory.
Create a .htaccess
file your Laravel root directory if it does not exists already. (Normally it is under your public_html
folder)
Edit the .htaccess file so that it contains the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Now you should be able to access the website without the "/public/index.php/" part.
Make a new folder in your root directory and move all the files and folder except public folder. You can call it anything you want. I'll use "laravel_code".
Next, move everything out of the public directory and into the root folder. It should result in something somewhat similar to this:
After that, all we have to do is edit the locations in the laravel_code/bootstrap/paths.php
file and the index.php
file.
In laravel_code/bootstrap/paths.php
find the following line of code:
'app' => __DIR__.'/../app',
'public' => __DIR__.'/../public',
And change them to:
'app' => __DIR__.'/../app',
'public' => __DIR__.'/../../',
In index.php
, find these lines:
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/start.php';
And change them to:
require __DIR__.'/laravel_code/bootstrap/autoload.php';
$app = require_once __DIR__.'/laravel_code/bootstrap/start.php';
The manual for GNU Make gives a clear definition for all
in its list of standard targets.
If the author of the Makefile is following that convention then the target all
should:
make
should do the same as make all
.To achieve 1 all
is typically defined as a .PHONY
target that depends on the executable(s) that form the entire program:
.PHONY : all
all : executable
To achieve 2 all
should either be the first target defined in the make file or be assigned as the default goal:
.DEFAULT_GOAL := all
I ran into the same problem. It seems that setting the cell.textlabel.text
property brings the UILabel to the front of the contentView of the cell.
Add the textView after setting textLabel.text
, or (if that's not possible) call this:
[cell.contentView bringSubviewToFront:textField]
Only one route enough for this
config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");
And need to specify attribute HttpGet or HttpPost in all actions.
[HttpGet]
public IEnumerable<object> TestGet1()
{
return new string[] { "value1", "value2" };
}
[HttpGet]
public IEnumerable<object> TestGet2()
{
return new string[] { "value3", "value4" };
}
First of all, add the System.Text
namespace
using System.Text;
Then use this code
string input = "some text";
byte[] array = Encoding.ASCII.GetBytes(input);
Hope to fix it!
For use variables in for example alter table:
DO $$
DECLARE name_pk VARCHAR(200);
BEGIN
select constraint_name
from information_schema.table_constraints
where table_schema = 'schema_name'
and table_name = 'table_name'
and constraint_type = 'PRIMARY KEY' INTO name_pk;
IF (name_pk := '') THEN
EXECUTE 'ALTER TABLE schema_name.table_name DROP CONSTRAINT ' || name_pk;
You can use $parent
to refer to the model defined in the parent scope like this
<input type="checkbox" ng-model="$parent.testb" />
Subclipse for Eclipse has an excellent graphical diff plugin if you are using SVN (subversion) source control.
This is the script I use. A bit tricky but it works. Tested on SQL Server 2012.
DECLARE @backupPath nvarchar(400);
DECLARE @sourceDb nvarchar(50);
DECLARE @sourceDb_log nvarchar(50);
DECLARE @destDb nvarchar(50);
DECLARE @destMdf nvarchar(100);
DECLARE @destLdf nvarchar(100);
DECLARE @sqlServerDbFolder nvarchar(100);
SET @sourceDb = 'db1'
SET @sourceDb_log = @sourceDb + '_log'
SET @backupPath = 'E:\tmp\' + sourceDb + '.bak' --ATTENTION: file must already exist and SQL Server must have access to it
SET @sqlServerDbFolder = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\'
SET @destDb = 'db2'
SET @destMdf = @sqlServerDbFolder + @destDb + '.mdf'
SET @destLdf = @sqlServerDbFolder + @destDb + '_log' + '.ldf'
BACKUP DATABASE @sourceDb TO DISK = @backupPath
RESTORE DATABASE @destDb FROM DISK = @backupPath
WITH REPLACE,
MOVE @sourceDb TO @destMdf,
MOVE @sourceDb_log TO @destLdf
<body>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
<script type="text/javascript">
var i = 0;
function incNumber() {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById("display").innerHTML = i;
}
function decNumber() {
if (i > 0) {
--i;
} else if (i = 0) {
i = 10;
}
document.getElementById("display").innerHTML = i;
}
</script>
</body>
It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.
You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.
Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
You can't convert an integer value straight to a date but you can first it to a datetime then to a date type
select cast(40835 as datetime)
and then convert to a date (SQL 2008)
select cast(cast(40835 as datetime) as date)
cheers
I don't know I used random.shuffle()
but it return 'None' to me, so I wrote this, might helpful to someone
def shuffle(arr):
for n in range(len(arr) - 1):
rnd = random.randint(0, (len(arr) - 1))
val1 = arr[rnd]
val2 = arr[rnd - 1]
arr[rnd - 1] = val1
arr[rnd] = val2
return arr
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
The Bearer
authentication scheme is what you are looking for.
Is it related to bears?
Errr... No :)
According to the Oxford Dictionaries, here's the definition of bearer:
bearer /'b??r?/
noun
A person or thing that carries or holds something.
A person who presents a cheque or other order to pay money.
The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.
And here's the definition of bearer token according to the RFC 6750:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer
authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer
scheme for access tokens in applications that don't use OAuth 2.0.
Stick to the standards as much as you can and don't create your own authentication schemes.
An access token must be sent in the Authorization
request header using the Bearer
authentication scheme:
2.1. Authorization Request Header Field
When sending the access token in the
Authorization
request header field defined by HTTP/1.1, the client uses theBearer
authentication scheme to transmit the access token.For example:
GET /resource HTTP/1.1 Host: server.example.com Authorization: Bearer mF_9.B5f-4.1JqM
[...]
Clients SHOULD make authenticated requests with a bearer token using the
Authorization
request header field with theBearer
HTTP authorization scheme. [...]
In case of invalid or missing token, the Bearer
scheme should be included in the WWW-Authenticate
response header:
3. The WWW-Authenticate Response Header Field
If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP
WWW-Authenticate
response header field [...].All challenges defined by this specification MUST use the auth-scheme value
Bearer
. This scheme MUST be followed by one or more auth-param values. [...].For example, in response to a protected resource request without authentication:
HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="example"
And in response to a protected resource request with an authentication attempt using an expired access token:
HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="example", error="invalid_token", error_description="The access token expired"
Use:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):
List<String> x = Arrays.asList("xyz", "abc");
Note: you can also use a static import if you like, then it looks like this:
import static java.util.Arrays.asList;
...
List<String> x = new ArrayList<>(asList("xyz", "abc"));
or
List<String> x = asList("xyz", "abc");
You could do it with jQuery.
$('.myClass').click(function() {
alert('hohoho');
});
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.
It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if
string s = "hello";
string t = "hello";
bool b = (s == t);
set b
to be false
? Imagine how difficult coding just about any application would be.
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
return false
is usually meant to terminate the object creation with a failure. It is as simple as that.
I agree with chrylis: you believe you changed your project's compliance settings but probably you didnt.
Right click on your project and:
By the way you can "tell" eclipse that jre8 is 1.6 compliance clicking on Window/Preferences/Java/Installed JREs/Execution Environment and selecting in the left panel, Execution Environments, JavaSE-1.6 and in the Compatible JRE's panel, jre8
just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.
I had this problem while working on java code to do process on a excel file containing a data set, then convert it to .csv file, i tried answers to this post, but they did not work. the problem was the jar files themselves. after downloading needed jar files one by one(older releases) and add them to my project, "source not found" error vanished. maybe you can check your jar files. hope this would help.
i'am working with hibernate 5 and postgres, and this worked form me.
@Column(name = "ACCOUNT_TYPE", ***nullable***=false, columnDefinition="varchar2 default 'END_USER'")
@Enumerated(EnumType.STRING)
private AccountType accountType;
Create a linked server to the source server. The easiest way is to right click "Linked Servers" in Management Studio; it's under Management -> Server Objects.
Then you can copy the table using a 4-part name, server.database.schema.table
:
select *
into DbName.dbo.NewTable
from LinkedServer.DbName.dbo.OldTable
This will both create the new table with the same structure as the original one and copy the data over.
This answer builds on Zach Smith's answer by resetting the identity column as well:
Here is the query:
-- Disable all constraints in the database
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
declare @catalog nvarchar(250);
declare @schema nvarchar(250);
declare @tbl nvarchar(250);
DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where
TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME != 'sysdiagrams'
AND TABLE_NAME != '__RefactorLog'
-- Optional
-- AND (TABLE_SCHEMA = 'dbo')
OPEN i;
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
/* Make sure these are the commands you want to execute before executing */
PRINT 'Executing statement: ' + @sql
--EXECUTE sp_executesql @sql
-- Reset identity counter if one exists
IF ((SELECT OBJECTPROPERTY( OBJECT_ID(@catalog + '.' + @schema + '.' + @tbl), 'TableHasIdentity')) = 1)
BEGIN
SET @sql = N'DBCC CHECKIDENT ([' + @catalog + '.' + @schema + '.' + @tbl + '], RESEED, 0)'
PRINT 'Executing statement: ' + @sql
--EXECUTE sp_executesql @sql
END
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
END
CLOSE i;
DEALLOCATE i;
-- Re-enable all constraints again
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
If you are using modal segue, make sure to set it as this image (you can turn off animation if you want)
No you don't need to check if you're in the main thread. Here is how you can do this in Swift:
runThisInMainThread { () -> Void in
runThisInMainThread { () -> Void in
// No problem
}
}
func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions
It's the correct way to access linked DB:
EXEC [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'
But make sure to mention dbo
as it owns the sp_helptext
.
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
The simplest approach is to encapsulate the two values together into a type which has both the image and the file. Then build an ArrayList
of that and shuffle it.
That improves encapsulation as well, giving you the property that you'll always have the same number of files as images automatically.
An alternative if you really don't like that idea would be to write the shuffle code yourself (there are plenty of examples of a modified Fisher-Yates shuffle in Java, including several on Stack Overflow I suspect) and just operate on both lists at the same time. But I'd strongly recommend going with the "improve encapsulation" approach.
Using CentOS 7's default mailx (appears as heirloom-mailx), I've simplified this to just using a text file with your required headers and a static boundary for multipart/mixed and multipart/alternative setup.
I'm sure you can figure out multipart/related if you want with the same setup.
test.txt:
--000000000000f3b2150570186a0e
Content-Type: multipart/alternative; boundary="000000000000f3b2130570186a0c"
--000000000000f3b2130570186a0c
Content-Type: text/plain; charset="UTF-8"
This is my plain text stuff here, in case the email client does not support HTML or is blocking it purposely
My Link Here <http://www.example.com>
--000000000000f3b2130570186a0c
Content-Type: text/html; charset="UTF-8"
<div dir="ltr">
<div>This is my HTML version of the email</div>
<div><br></div>
<div><a href="http://www.example.com">My Link Here</a><br></div>
</div>
--000000000000f3b2130570186a0c--
--000000000000f3b2150570186a0e
Content-Type: text/csv; charset="US-ASCII"; name="test.csv"
Content-Disposition: attachment; filename="test.csv"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_jj5qmzqz0
The boundaries define multipart segments.
The boundary ID that has no dashes at the end is a start point of a segment.
The one with the two dashes at the end is the end point.
In this example, there's a subpart within the multipart/mixed main section, for multipart/alternative.
The multipart/alternative method basically says "Fallback to this, IF the priority part does not succeed" - in this example HTML is taken as priority normally by email clients. If an email client won't display the HTML, it falls back to the plain text.
The multipart/mixed method which encapsulates this whole message, is basically saying there's different content here, display both.
In this example, I placed a CSV file attachment on the email. You'll see the attachment get plugged in using base64 in the command below.
I threw in the attachment as an example, you'll have to set your content type appropriately for your attachment and specify whether inline or not.
The X-Attachment-Id is necessary for some providers, randomize the ID you set.
The command to mail this is:
echo -e "`cat test.txt; openssl base64 -e < test.csv`\n--000000000000f3b2150570186a0e--\n" | mailx -s "Test 2 $( echo -e "\nContent-Type: multipart/mixed; boundary=\"000000000000f3b2150570186a0e\"" )" -r [email protected] [email protected]
As you can see in the mailx Subject line I insert the multipart boundary statically, this is the first header the email client will see.
Then comes the test.txt contents being dumped.
Regarding the attachment, I use openssl (which is pretty standard on systems) to convert the file attachment to base64.
Additionally, I added the boundary close statement at the end of this echo, to signify the end of the message.
This works around heirloom-mailx problems and is virtually script-less.
The echo can be a feed instead, or any other number of methods.
In Swift 3 / iOS 10+ this now looks like
if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
UIApplication.shared.open(url, completionHandler: .none)
}
If your database is straightforward and simple, LINQ to SQL will do. If you need logical/abstracted entities on top of your tables, then go for Entity Framework.
This error occurs when you resolve the conflicts but the file still needs to be added in the stage area. git add . would solve it. Then, try to commit and merge.
git fetch
git branch --track branch-name origin/branch-name
First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin
and branch name is branch-name
.
--track
option is enabled by default for remote branches and you can omit it.
something like....
SELECT f.*
,a1.city as from
,a2.city as to
FROM flights f
INNER JOIN airports a1
ON f.fairport = a1. code
INNER JOIN airports a2
ON f.tairport = a2. code
[[ -s file ]] --> Checks if file has size greater than 0
if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
If needed, this checks all the *.txt files in the current directory; and reports all the empty file:
for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done
In your main layout set your ListView
gravity to right:
android:layout_gravity="right"
Also in your code :
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
}
else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
};
hope it works :)
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 would use a negative lookahead for any character:
^(?![\s\S])
This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.
You can achieve an expected result with requests
library as well:
import requests
url = "http://www.mywebsite.org/Data%20Set.zip"
print(f"Before: {url}")
print(f"After: {requests.utils.unquote(url)}")
Output:
$ python3 test_url_unquote.py
Before: http://www.mywebsite.org/Data%20Set.zip
After: http://www.mywebsite.org/Data Set.zip
Might be handy if you are already using requests
, without using another library for this job.
You could also come up with something like this!
def get_logger(name=None):
default = "__app__"
formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
log_map = {"__app__": "app.log", "__basic_log__": "file1.log", "__advance_log__": "file2.log"}
if name:
logger = logging.getLogger(name)
else:
logger = logging.getLogger(default)
fh = logging.FileHandler(log_map[name])
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.setLevel(logging.DEBUG)
return logger
Now you could use multiple loggers in same module and across whole project if the above is defined in a separate module and imported in other modules were logging is required.
a=get_logger("__app___")
b=get_logger("__basic_log__")
a.info("Starting logging!")
b.debug("Debug Mode")
No one commenting on the randomAge
method?
This is so awfully wrong, it couldn't be any wronger.
NSInteger
is a primitive type - it is most likely typedef'd as int
or long
.
In the randomAge
method, you calculate a number from about 1 to 98.
Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.
If you access an NSInteger
through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.
Change it either to NSInteger
or int
, which is probably the best, or to NSNumber
if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.
Array into table. Array into div. JSON into table. JSON into div.
All are nicely handle this class. Click here to get a class
How to use it?
Just get and object
$obj = new Arrayinto();
Create an array you want to convert
$obj->array_object = array("AAA" => "1111",
"BBB" => "2222",
"CCC" => array("CCC-1" => "123",
"CCC-2" => array("CCC-2222-A" => "CA2",
"CCC-2222=B" => "CB2"
)
)
);
If you want to convert Array into table. Call this.
$result = $obj->process_table();
If you want to convert Array into div. Call this.
$result = $obj->process_div();
Let suppose if you have a JSON
$obj->json_string = '{
"AAA":"11111",
"BBB":"22222",
"CCC":[
{
"CCC-1":"123"
},
{
"CCC-2":"456"
}
]
}
';
You can convert into table/div like this
$result = $obj->process_json('div');
OR
$result = $obj->process_json('table');
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
Remove Postmaster file in "C:\Program Files\PostgreSQL\9.6\data"
and restart the PostgreSQL services
If you want the time as well, just go with
datetime.datetime.now().__str__()
Prints 2019-07-11 19:36:31.118766
in console for me
For more info on this click here.
Example
<div id="header_id" class="header_class">Text</div>
#header_id {font-color:#fff}
.header_class {font-color:#000}
(Note that CSS uses the prefix # for IDs and . for Classes.)
However color
was an HTML 4.01 <font>
tag attribute deprecated in HTML 5.
In CSS there is no "font-color", the style is color
so the above should read:
Example
<div id="header_id" class="header_class">Text</div>
#header_id {color:#fff}
.header_class {color:#000}
The text would be white.
I will share that How do I do it since Java 7 -
Long first = 12345L, second = 123L;
System.out.println(first.equals(second));
output returned : false
and second example of match is -
Long first = 12345L, second = 12345L;
System.out.println(first.equals(second));
output returned : true
So, I believe in equals method for comparing Object's value, Hope it helps you, thanks.
Ages ago, in November 2005, AlistApart.com published an article on how they published a book using nothing but HTML and CSS. See: http://alistapart.com/article/boom
Here's an excerpt of that article:
CSS2 has a notion of paged media (think sheets of paper), as opposed to continuous media (think scrollbars). Style sheets can set the size of pages and their margins. Page templates can be given names and elements can state which named page they want to be printed on. Also, elements in the source document can force page breaks. Here is a snippet from the style sheet we used:
@page { size: 7in 9.25in; margin: 27mm 16mm 27mm 16mm; }
Having a US-based publisher, we were given the page size in inches. We, being Europeans, continued with metric measurements. CSS accepts both.
After setting the up the page size and margin, we needed to make sure there are page breaks in the right places. The following excerpt shows how page breaks are generated after chapters and appendices:
div.chapter, div.appendix { page-break-after: always; }
Also, we used CSS2 to declare named pages:
div.titlepage { page: blank; }
That is, the title page is to be printed on pages with the name “blank.” CSS2 described the concept of named pages, but their value only becomes apparent when headers and footers are available.
Anyway…
Since you want to print A4, you'll need different dimensions of course:
@page {
size: 21cm 29.7cm;
margin: 30mm 45mm 30mm 45mm;
/* change the margins as you want them to be. */
}
The article dives into things like setting page-breaks, etc. so you might want to read that completely.
In your case, the trick is to create the print CSS first. Most modern browsers (>2005) support zooming and will already be able to display a website based on the print CSS.
Now, you'll want to make the web display look a bit different and adapt the whole design to fit most browsers too (including the old, pre 2005 ones). For that, you'll have to create a web CSS file or override some parts of your print CSS. When creating CSS for web display, remember that a browser can have ANY size (think: “mobile” up to “big-screen TVs”). Meaning: for the web CSS your page-width and image-width is best set using a variable width (%) to support as many display devices and web-browsing clients as possible.
EDIT (26-02-2015)
Today, I happened to stumble upon another, more recent article at SmashingMagazine which also dives into designing for print with HTML and CSS… just in case you could use yet-another-tutorial.
EDIT (30-10-2018)
It has been brought to my attention in that size
is not valid CSS3, which is indeed correct — I merely repeated the code quoted in the article which (as noted) was good old CSS2 (which makes sense when you look at the year the article and this answer were first published). Anyway, here's the valid CSS3 code for your copy-and-paste convenience:
@media print {
body{
width: 21cm;
height: 29.7cm;
margin: 30mm 45mm 30mm 45mm;
/* change the margins as you want them to be. */
}
}
In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:
Yet, I would avoid the hassle and simply use cm
(centimeters) or mm
(millimeters) for sizing as that avoids rendering glitches that can arise depending on which client you use.
Git will recognise the file from the contents, rather than seeing it as a new untracked file
That's where you went wrong.
It's only after you add the file, that git will recognize it from content.
An ugly solution that works like a charm for me:
$("#mydialog").dialog(
open: function(){
$('div.ui-widget-overlay').hide();
$("div.ui-dialog").not(':first').remove();
}
});
Since TypeScript 3.7 was released you can use optional chaining now.
Property example:
let x = foo?.bar.baz();
This is equvalent to:
let x = (foo === null || foo === undefined) ?
undefined :
foo.bar.baz();
Moreover you can call:
Optional Call
function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
otherFn will be called only if otherFn won't be equal to null or undefined
Usage optional chaining in IF statement
This:
if (someObj && someObj.someProperty) {
// ...
}
can be replaced now with this
if (someObj?.someProperty) {
// ...
}
Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
=RIGHT(A1,LEN(A1)-FIND("`*`",SUBSTITUTE(A1," ","`*`",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))
this is probably about you don't entered correct dependency version. you can select correct dependency from this:
file>menu>project structure>app>dependencies>+>Library Dependency>select any thing you need > OK
if cannot find your needs you should update your sdk from below way:
tools>android>sdk manager>sdk update>select any thing you need>ok
It looks like you are missing including the IOBluetooth.framework in your project. You can add it by:
Clicking on your project in the upper left of the left pane (the blue icon).
In the middle pane, click on the Build Phases tab.
Under "Link Binary With Libraries", click on the plus button.
Find the IOBluetooth.framework from the list and hit Add.
This will make sure that the IOBluetooth.framework definitions are found by the linker. You can see that the framework is a member of your target by clicking on the framework in the left pane and seeing the framework's target membership in the right pane (note I've moved the framework under the Frameworks group for organization purposes):
Here is another variation for a file upload that has a nicer looking bootstrap button than the default file upload browse button. This is the html:
<div class="form-group">
@Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "col-md-2 control-label" })
<div class="col-md-1 btn btn-sn btn-primary" id="browseButton" onclick="$(this).parent().find('input[type=file]').click();">browse</div>
<div class="col-md-7">
<input id="fileSpace" name="uploaded_file" type="file" style="display: none;"> @*style="display: none;"*@
@Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control", @id = "modelField"} })
@Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
</div>
</div>
Here is the script:
$('#fileSpace').on("change", function () {
$("#modelField").val($('input[name="uploaded_file"]').val());
In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...
Operating off the assumption that we have a file named jsonConfigFile.json
with the following content from your post:
{
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]@{}
(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
ForEach-Object { $json[$_.Name] = $_.Value }
$json.Stuffs
will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type
key's value associated with the Clean Toilet
key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.
If "read its contents into a string" means that the file does not contain characters with code 0, you can also use getdelim() function, that either accepts a block of memory and reallocates it if necessary, or just allocates the entire buffer for you, and reads the file into it until it encounters a specified delimiter or end of file. Just pass '\0' as the delimiter to read the entire file.
This function is available in the GNU C Library, http://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getdelim-994
The sample code might look as simple as
char* buffer = NULL;
size_t len;
ssize_t bytes_read = getdelim( &buffer, &len, '\0', fp);
if ( bytes_read != -1) {
/* Success, now the entire file is in the buffer */
Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.
Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.
Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.
I've only tried this on Python 2, but I think it should work fine on 3 as well:
import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email(subject, message, from_email, to_email=[], attachment=[]):
"""
:param subject: email subject
:param message: Body content of the email (string), can be HTML/CSS or plain text
:param from_email: Email address from where the email is sent
:param to_email: List of email recipients, example: ["[email protected]", "[email protected]"]
:param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
"""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ", ".join(to_email)
msg.attach(MIMEText(message, 'html'))
for f in attachment:
with open(f, 'rb') as a_file:
basename = os.path.basename(f)
part = MIMEApplication(a_file.read(), Name=basename)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename
msg.attach(part)
email = smtplib.SMTP('your-smtp-host-name.com')
email.sendmail(from_email, to_email, msg.as_string())
I hope this helps! :-)
If you are creating an array then there is no difference, however, the following is neater:
String[] suit = {
"spades",
"hearts",
"diamonds",
"clubs"
};
But, if you want to pass an array into a method you have to call it like this:
myMethod(new String[] {"spades", "hearts"});
myMethod({"spades", "hearts"}); //won't compile!
Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute
and DataMemberAttribute
, found in the System.Runtime.Serialization namespace.
The DataContactAttribute
is applied to the class, and the DataMemberAttribute
is applied to each member you want to be serialized:
[DataContract]
public class MyClass {
[DataMember]
public int Id { get; set;} // Serialized
[DataMember]
public string Name { get; set; } // Serialized
public string DontExposeMe { get; set; } // Will not be serialized
}
Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.
Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.
That being said, the following works...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then((res: Actor) => {
// res is now an Actor
});
I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...
callBack: (response: any) => void
But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then(res => {
if (callback) {
callback(res); // Client receives the response as desired type.
}
});
So that a client can call it with a callback like...
(response: IApigeeResponse) => {
// Process response as an IApigeeResponse
}
You are trying to delete a row that is referenced by another row (possibly in another table).
You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
For the basic (the current week's Sunday)
select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) as date)
If previous week:
select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) -7 as date)
Internally, we built a function that does it but if you need quick and dirty, this will do it.
nullptr
is always a pointer type. 0
(aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:
f(int);
f(foo *);
df.ix[10,:]
gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]
. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive
The official method. No custom CSS required :
<form class="form-inline" role="form">
<div class="form-group has-success has-feedback">
<label class="control-label" for="inputSuccess4"></label>
<input type="text" class="form-control" id="inputSuccess4">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</form>
DEMO : http://jsfiddle.net/yajf3b7q
This demo is based on an example in Bootstrap docs. Scroll down to "With Optional Icons" here http://getbootstrap.com/css/#forms-control-validation
Look at real_ates
ES2016 way, it's more correct.
import crypto from 'crypto';
function spawnTokenBuf() {
return function(callback) {
crypto.randomBytes(48, callback);
};
}
async function() {
console.log((await spawnTokenBuf()).toString('base64'));
};
var crypto = require('crypto');
var co = require('co');
function spawnTokenBuf() {
return function(callback) {
crypto.randomBytes(48, callback);
};
}
co(function* () {
console.log((yield spawnTokenBuf()).toString('base64'));
});
Message queues are asynchronous and can retry a number of times if delivery fails. Use a message queue if the requester doesn't need to wait for a response.
The phrase "web services" make me think of synchronous calls to a distributed component over HTTP. Use web services if the requester needs a response back.
/* Most Accurate Setting if you only want
to do this with CSS Pseudo Element */
p:before {
content: "\00a0";
padding-right: 5px; /* If you need more space b/w contents */
}
lazy-init is the attribute of bean. The values of lazy-init can be true and false. If lazy-init is true, then that bean will be initialized when a request is made to bean. This bean will not be initialized when the spring container is initialized and if lazy-init is false then the bean will be initialized with the spring container initialization.
Since Bootstrap v4.1 you can add table-borderless
to your table, see official documentation:
<table class='table table-borderless'>
You can also do this with ant contrib's if task.
<if>
<equals arg1="${condition}" arg2="true"/>
<then>
<copy file="${some.dir}/file" todir="${another.dir}"/>
</then>
<elseif>
<equals arg1="${condition}" arg2="false"/>
<then>
<copy file="${some.dir}/differentFile" todir="${another.dir}"/>
</then>
</elseif>
<else>
<echo message="Condition was neither true nor false"/>
</else>
</if>
Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz
Then Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm
This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.
This code should do the trick:
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
Actually I work on project compatible python 2.6, 2.7 and 3.4 and I have to create IDs from free user entries.
Thanks to you, I have created this function that works wonders.
import re
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = unicode(text, 'utf-8')
except (TypeError, NameError): # unicode is a default on python 3
pass
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
return str(text)
def text_to_id(text):
"""
Convert input text to id.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = strip_accents(text.lower())
text = re.sub('[ ]+', '_', text)
text = re.sub('[^0-9a-zA-Z_-]', '', text)
return text
result:
text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889")
>>> 'montreal_uber_1289_mere_francoise_noel_889'
This css solution worked for me:
input:active,
input:focus {
border: 1px solid #red
}
input:active,
input:focus {
padding: 2px solid #red /*for firefox and chrome*/
}
/* .ie is a class you would need to set at the html root level */
.ie input:active,
.ie input:focus {
padding: 3px solid #red /* IE needs 1px extra padding*/
}
I understand it is not necessary on FF and Chrome, but IE needs it. And there are circumstances when you need it.
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
FractionallySizedBox
may also be useful.
You can also read the screen width directly out of MediaQuery.of(context).size
and create a sized box based on that
MediaQuery.of(context).size.width * 0.65
if you really want to size as a fraction of the screen regardless of what the layout is.
When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.
SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";
If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.
SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';
Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.
It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.
SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";
An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:
var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
jDepthLvl++;
if (isIterable(object)) {
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
} else
console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
forEachIn(object, function (accessor, child) {
visit(child, accessor);
});
} else {
var value = object;
console.log("%c"
+ spacesDepth(jDepthLvl)
+ objectAccessor + "[%c" + value + "%c] "
,"color:blue","color:red","color:blue");
}
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
}
jDepthLvl--;
}
function spacesDepth(jDepthLvl) {
let jSpc="";
for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
jSpc+="\u0020\u0020"
}
return jSpc;
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
visit($OBJECT_OR_ARRAY$);
this one is working for me also for internet explorer:
<div class="col imagebox" [ngStyle]="bkUrl"></div>
...
@Input() background = '571x450img';
bkUrl = {};
ngOnInit() {
this.bkUrl = this.getBkUrl();
}
getBkUrl() {
const styles = {
'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
};
console.log(styles);
return styles;
}
Just a MacOS extra update for hjpotter92 answer.
To make sed
recognize the pattern in MacOS, you'll have to add a backslash before the =
sign, like this:
sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql
If you want a control to postback automatically when an event is raised, you need to set the AutoPostBack property of the control to True.