You didn't want an Excel-based solution but since I had the same problem today and wanted to test using other Office Applications functions I wrote the function below.
Limitations:
Tested calling Excel 2010 from Visio 2010
Option Base 1
Private Function sort_array_2D_excel(array_2D, array_sortkeys, Optional array_sortorders, Optional tag_header As String = "Guess", Optional tag_matchcase As String = "False")
' Dependencies: Excel; Tools > References > Microsoft Excel [Version] Object Library
Dim excel_application As Excel.Application
Dim excel_workbook As Excel.Workbook
Dim excel_worksheet As Excel.Worksheet
Set excel_application = CreateObject("Excel.Application")
excel_application.Visible = True
excel_application.ScreenUpdating = False
excel_application.WindowState = xlNormal
Set excel_workbook = excel_application.Workbooks.Add
excel_workbook.Activate
Set excel_worksheet = excel_workbook.Worksheets.Add
excel_worksheet.Activate
excel_worksheet.Visible = xlSheetVisible
Dim excel_range As Excel.Range
Set excel_range = excel_worksheet.Range("A1").Resize(UBound(array_2D, 1) - LBound(array_2D, 1) + 1, UBound(array_2D, 2) - LBound(array_2D, 2) + 1)
excel_range = array_2D
For i_sortkey = LBound(array_sortkeys) To UBound(array_sortkeys)
If IsNumeric(array_sortkeys(i_sortkey)) Then
sortkey_range = Chr(array_sortkeys(i_sortkey) + 65 - 1) & "1"
Set array_sortkeys(i_sortkey) = excel_worksheet.Range(sortkey_range)
Else
MsgBox "Error in sortkey parameter:" & vbLf & "array_sortkeys(" & i_sortkey & ") = " & array_sortkeys(i_sortkey) & vbLf & "Terminating..."
End
End If
Next i_sortkey
For i_sortorder = LBound(array_sortorders) To UBound(array_sortorders)
Select Case LCase(array_sortorders(i_sortorder))
Case "asc"
array_sortorders(i_sortorder) = XlSortOrder.xlAscending
Case "desc"
array_sortorders(i_sortorder) = XlSortOrder.xlDescending
Case Else
array_sortorders(i_sortorder) = XlSortOrder.xlAscending
End Select
Next i_sortorder
Select Case LCase(tag_header)
Case "yes"
tag_header = Excel.xlYes
Case "no"
tag_header = Excel.xlNo
Case "guess"
tag_header = Excel.xlGuess
Case Else
tag_header = Excel.xlGuess
End Select
Select Case LCase(tag_matchcase)
Case "true"
tag_matchcase = True
Case "false"
tag_matchcase = False
Case Else
tag_matchcase = False
End Select
Select Case (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)
Case 1
Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Header:=tag_header, MatchCase:=tag_matchcase)
Case 2
Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Header:=tag_header, MatchCase:=tag_matchcase)
Case 3
Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Key3:=array_sortkeys(3), Order3:=array_sortorders(3), Header:=tag_header, MatchCase:=tag_matchcase)
Case Else
MsgBox "Error in sortkey parameter:" & vbLf & "Maximum number of sort columns is 3!" & vbLf & "Currently passed: " & (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)
End
End Select
For i_row = 1 To excel_range.Rows.Count
For i_column = 1 To excel_range.Columns.Count
array_2D(i_row, i_column) = excel_range(i_row, i_column)
Next i_column
Next i_row
excel_workbook.Close False
excel_application.Quit
Set excel_worksheet = Nothing
Set excel_workbook = Nothing
Set excel_application = Nothing
sort_array_2D_excel = array_2D
End Function
Private Sub test_sort()
array_unsorted = dim_sort_array()
Call msgbox_array(array_unsorted)
array_sorted = sort_array_2D_excel(array_unsorted, Array(2, 1, 3), Array("desc", "", "asdas"), "yes", "False")
Call msgbox_array(array_sorted)
End Sub
Private Function dim_sort_array()
Dim array_unsorted(1 To 5, 1 To 3) As String
i_row = 0
i_row = i_row + 1
array_unsorted(i_row, 1) = "Column1": array_unsorted(i_row, 2) = "Column2": array_unsorted(i_row, 3) = "Column3"
i_row = i_row + 1
array_unsorted(i_row, 1) = "OR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
i_row = i_row + 1
array_unsorted(i_row, 1) = "XOR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
i_row = i_row + 1
array_unsorted(i_row, 1) = "NOT": array_unsorted(i_row, 2) = "B": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
i_row = i_row + 1
array_unsorted(i_row, 1) = "AND": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
dim_sort_array = array_unsorted
End Function
Sub msgbox_array(array_2D, Optional string_info As String = "2D array content:")
msgbox_string = string_info & vbLf
For i_row = LBound(array_2D, 1) To UBound(array_2D, 1)
msgbox_string = msgbox_string & vbLf & i_row & vbTab
For i_column = LBound(array_2D, 2) To UBound(array_2D, 2)
msgbox_string = msgbox_string & array_2D(i_row, i_column) & vbTab
Next i_column
Next i_row
MsgBox msgbox_string
End Sub
If anybody tests this using other versions of office please post here if there are any problems.
Use HTML's anchors:
Main Page:
<a href="sample.html#sushi">Sushi</a>
<a href="sample.html#bbq">BBQ</a>
Sample Page:
<div id='sushi'><a name='sushi'></a></div>
<div id='bbq'><a name='bbq'></a></div>
For examle
git stash show --name-only
result
ofbiz_src/.project
ofbiz_src/applications/baseaccounting/entitydef/entitymodel_view.xml
ofbiz_src/applications/baselogistics/webapp/baselogistics/delivery/purchaseDeliveryDetail.ftl
ofbiz_src/applications/baselogistics/webapp/baselogistics/transfer/listTransfers.ftl
ofbiz_src/applications/component-load.xml
ofbiz_src/applications/search/config/elasticSearch.properties
ofbiz_src/framework/entity/lib/jdbc/mysql-connector-java-5.1.46.jar
ofbiz_src/framework/entity/lib/jdbc/postgresql-9.3-1101.jdbc4.jar
Then pop stash in specific file
git checkout stash@{0} -- ofbiz_src/applications/baselogistics/webapp/baselogistics/delivery/purchaseDeliveryDetail.ftl
other related commands
git stash list --stat
get stash show
FOR EL CAPITAN
rvm install ruby-2.2.2.
rvm use ruby-2.2.2.
sudo gem install -n /usr/local/bin cocoapods
For url like https://myapp.com/user/666/read?age=23 use
import { combineLatest } from 'rxjs';
// ...
combineLatest( [this.route.paramMap, this.route.queryParamMap] )
.subscribe( ([pathParams, queryParams]) => {
let userId = pathParams.get('userId'); // =666
let age = queryParams.get('age'); // =23
// ...
})
In case when you use this.router.navigate([someUrl]);
and your query parameters are embedded in someUrl
string then angular encodes a URL and you get something like this https://myapp.com/user/666/read%3Fage%323 - and above solution will give wrong result (queryParams will be empty, and path params can be glued to last path param if it is on the path end). In this case change the way of navigation to this
this.router.navigateByUrl(someUrl);
Use .val()
not attr('value')
.
I use /bin/zsh
, and I changed vscode to do the same, but somehow vscode still use the path from /bin/bash
. So I created a .bash_profile file with node location in the path.
Simply run in terminal:
echo "PATH=$PATH
export \$PATH" >> ~/.bash_profile
Restart vscode, and it will work.
This is the only thing I've found for JavaScript formatting in Dreamweaver. Not many options, but it seems to work well.
JavaScript source format extension for dreamweaver: Adobe CFusion
You can download from below link. ftp://ftp.comtrol.com/dev_mstr/sdk/other/1800136.tar.gz After downloading just extract the image and install.
Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.
Your new environment may have E_STRICT
warnings enabled in error_reporting
for PHP versions <= 5.3.x, or simply have error_reporting
set to at least E_WARNING
with PHP versions >= 5.4. That error is triggered when $res
is NULL
or not yet initialized:
$res = NULL;
$res->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $res
is already initialized to some value but is not an object:
$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object
In order to comply with E_STRICT
standards prior to PHP 5.4, or the normal E_WARNING
error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success
, you need to declare $res
as an object of stdClass
in the global namespace:
$res = new \stdClass();
$res->success = false;
You can do it like:
tvHide.setText(Html.fromHtml("<p><span style='text-decoration: underline'>Hide post</span></p>").toString());
Hope this helps
This is an ancient post, sorry, but I only came across it now and I wanted to give my solution to whoever might stumble upon this one day.
As some have mentioned, performing an INSERT
and then a DELETE
might lead to integrity issues, so perhaps a way to get around it, and to perform everything neatly in a single statement, is to take advantage of the [deleted]
temporary table.
DELETE FROM [source]
OUTPUT [deleted].<column_list>
INTO [destination] (<column_list>)
Without the need to install the grep variant pcregrep, you can do multiline search with grep.
$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c
Explanation:
-P
activate perl-regexp for grep (a powerful extension of regular expressions)
-z
suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.
-o
print only matching. Because we're using -z
, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.
In regexp:
(?s)
activate PCRE_DOTALL
, which means that .
finds any character or newline
\N
find anything except newline, even with PCRE_DOTALL
activated
.*?
find .
in non-greedy mode, that is, stops as soon as possible.
^
find start of line
\1
backreference to the first group (\s*
). This is a try to find the same indentation of method.
As you can imagine, this search prints the main method in a C (*.c
) source file.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
It may be helpful to make an alias for it.
Install and find your tensorboard location:
pip install tensorboard
pip show tensorboard
Add the following alias in .bashrc:
alias tensorboard='python pathShownByPip/tensorboard/main.py'
Open another terminal or run exec bash.
For Windows users, cd into pathShownByPip\tensorboard
and run python main.py
from there.
For Python 3.x, use pip3
instead of pip
, and don't forget to use python3
in the alias.
In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):
Inspect element and then click on the three white dots in the left gutter:
You can do it faster without any imports just by using magics:
%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0
Notice that all env variable are strings, so no need to use "
. You can verify that env-variable is set up by running: %env <name_of_var>
. Or check all of them with %env
.
There is a manual page dedicated to help choosing between mysql, mysqli and PDO at
The PHP team recommends mysqli or PDO_MySQL for new development:
It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.
The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:
mysqli mysql
Development Status Active Maintenance only
Lifecycle Active Long Term Deprecation Announced*
Recommended Yes No
OOP API Yes No
Asynchronous Queries Yes No
Server-Side Prep. Statements Yes No
Stored Procedures Yes No
Multiple Statements Yes No
Transactions Yes No
MySQL 5.1+ functionality Yes No
* http://news.php.net/php.internals/53799
There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at
and a very thorough blog article at
You can control client cache with HTTP headers. This works in any web framework.
You can set the directives these headers to have fine grained control over how and when to enable|disable cache:
Cache-Control
Surrogate-Control
Expires
ETag
(very good one)Pragma
(if you want to support old browsers)Good caching is good, but very complex, in all computer systems. Take a look at https://helmetjs.github.io/docs/nocache/#the-headers for more information.
.selector{
background-size: cover;
/* stretches background WITHOUT deformation so it would fill the background space,
it may crop the image if the image's dimensions are in different ratio,
than the element dimensions. */
}
Max. stretch without crop nor deformation (may not fill the background): background-size: contain;
Force absolute stretch (may cause deformation, but no crop): background-size: 100% 100%;
Absolute positioning image as a first child of the (relative positioned) parent and stretching it to the parent size.
HTML
<div class="selector">
<img src="path.extension" alt="alt text">
<!-- some other content -->
</div>
background-size: cover;
:To achieve this dynamically, you would have to use the opposite of contain method alternative (see below) and if you need to center the cropped image, you would need a JavaScript to do that dynamically - e.g. using jQuery:
$('.selector img').each(function(){
$(this).css({
"left": "50%",
"margin-left": "-"+( $(this).width()/2 )+"px",
"top": "50%",
"margin-top": "-"+( $(this).height()/2 )+"px"
});
});
Practical example:
background-size: contain;
:This one can be a bit tricky - the dimension of your background that would overflow the parent will have CSS set to 100% the other one to auto. Practical example:
.selector img{
position: absolute; top:0; left: 0;
width: 100%;
height: auto;
/* -- OR -- */
/* width: auto;
height: 100%; */
}
background-size: 100% 100%;
:.selector img{
position: absolute; top:0; left: 0;
width: 100%;
height: 100%;
}
PS: To do the equivalents of cover/contain in the "old" way completely dynamically (so you will not have to care about overflows/ratios) you would have to use javascript to detect the ratios for you and set the dimensions as described...
In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.
You can use \
to indicate that any line of Ruby continues on the next line. This works with strings too:
string = "this is a \
string that spans lines"
puts string.inspect
will output "this is a string that spans lines"
For generating the patches from the topmost commits from a specific sha1 hash:
git format-patch -<n> <SHA1>
The last 10 patches from head in a single patch file:
git format-patch -10 HEAD --stdout > 0001-last-10-commits.patch
Run the below commands and install the required packages globally:
npm install -g ts-node
npm install -g typescript
Now run the following command to execute a typescript file:
ts-node typescript-file.ts
if ( $("#checkSurfaceEnvironment-1").is(":checked") && $("#checkSurfaceEnvironment-2").not(":checked") )
The link below, gives a very good tutorial, about playing mp3 files from a windows form with c#:
http://www.daniweb.com/software-development/csharp/threads/292695/playing-mp3-in-c
This link will lead you to a topic, which contains a lot information about how to play an mp3 song, using Windows forms. It also contains a lot of other projects, trying to achieve the same thing:
For example use this code for .mp3:
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "My MP3 file.mp3";
wplayer.Controls.Play();
Then only put the wplayer.Controls.Play(); in the Button_Click event.
For example use this code for .wav:
System.Media.SoundPlayer player = new System.Media.SoundPlayer();
player.SoundLocation = "Sound.wav";
player.Play();
Put the player.Play(); in the Button_Click event, and it will work.
The command line arguments are separated by space. If you want provide an argument with a space in it, you should quote it. So use git commit -m "initial commit"
.
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
I assume Answer
as an Integer data type so in this case, you can easily use Scanner
class for adding the multiple elements(say 50).
private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S){
for (int i=0;i<50;i++) {
/*Using Scanner class object to take input.*/
arrayList.add(obj.nextInt());
}
/*You can also check the elements of your ArrayList.*/
for (int i=0;i<50;i++) {
/*Using get function for fetching the value present at index 'i'.*/
System.out.print(arrayList.get(i)+" ");
}}
This is a simple and easy method for adding multiple values in an ArrayList using for loop.
As in the above code, I presume the Answer
as Integer it could be String
, Double
, Long
et Cetra. So, in that case, you can use next()
, nextDouble()
, and nextLong()
respectively.
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
The ID always starts with 'post-' then the numbers are dynamic.
Please check your id names, "poll" and "post" are very different.
As already answered, you can use querySelector:
var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;
but querySelector will not find "poll" if you keep querying for "post": '[id^="post-"]'
A dplyr
solution (part of the tidyverse
package set) is to use select
:
select(table, "Time", "Out", "In", "Files")
# or
select(table, Time, Out, In, Files)
I use
if(is_numeric($value) && $value > 0 && $value == round($value, 0)){
to validate if a value is numeric, positive and integral
I don't really like ctype_digit as its not as readable as "is_numeric" and actually has less flaws when you really want to validate that a value is numeric.
This is what you would like to do:
OurKey.SetValue("Password", StringEncryptor.EncryptString(textBoxPassword.Text));
OurKey.GetValue("Password", StringEncryptor.DecryptString(textBoxPassword.Text));
You can do that with this the following classes. This class is a generic class is the client endpoint. It enables IOC of various encryption algorithms using Ninject.
public class StringEncryptor
{
private static IKernel _kernel;
static StringEncryptor()
{
_kernel = new StandardKernel(new EncryptionModule());
}
public static string EncryptString(string plainText)
{
return _kernel.Get<IStringEncryptor>().EncryptString(plainText);
}
public static string DecryptString(string encryptedText)
{
return _kernel.Get<IStringEncryptor>().DecryptString(encryptedText);
}
}
This next class is the ninject class that allows you to inject the various algorithms:
public class EncryptionModule : StandardModule
{
public override void Load()
{
Bind<IStringEncryptor>().To<TripleDESStringEncryptor>();
}
}
This is the interface that any algorithm needs to implement to encrypt/decrypt strings:
public interface IStringEncryptor
{
string EncryptString(string plainText);
string DecryptString(string encryptedText);
}
This is a implementation using the TripleDES algorithm:
public class TripleDESStringEncryptor : IStringEncryptor
{
private byte[] _key;
private byte[] _iv;
private TripleDESCryptoServiceProvider _provider;
public TripleDESStringEncryptor()
{
_key = System.Text.ASCIIEncoding.ASCII.GetBytes("GSYAHAGCBDUUADIADKOPAAAW");
_iv = System.Text.ASCIIEncoding.ASCII.GetBytes("USAZBGAW");
_provider = new TripleDESCryptoServiceProvider();
}
#region IStringEncryptor Members
public string EncryptString(string plainText)
{
return Transform(plainText, _provider.CreateEncryptor(_key, _iv));
}
public string DecryptString(string encryptedText)
{
return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));
}
#endregion
private string Transform(string text, ICryptoTransform transform)
{
if (text == null)
{
return null;
}
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
byte[] input = Encoding.Default.GetBytes(text);
cryptoStream.Write(input, 0, input.Length);
cryptoStream.FlushFinalBlock();
return Encoding.Default.GetString(stream.ToArray());
}
}
}
}
You can watch my video and download the code for this at : http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html
From the Apache Maven site
<project>
...
<repositories>
<repository>
<id>my-internal-site</id>
<url>http://myserver/repo</url>
</repository>
</repositories>
...
</project>
"The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml." - Apache Maven site - settings reference
<servers>
<server>
<id>server001</id>
<username>my_login</username>
<password>my_password</password>
<privateKey>${user.home}/.ssh/id_dsa</privateKey>
<passphrase>some_passphrase</passphrase>
<filePermissions>664</filePermissions>
<directoryPermissions>775</directoryPermissions>
<configuration></configuration>
</server>
</servers>
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
Try to target 1024 as the minimum width. Try how it looks at 800, but don't bother too much making that work. At 800x600 almost none of the major websites are going to work, so people working at that resolution are going to have problems all the time anyway.
If you're going to go for a liquid layout, make sure that text doesn't get too wide, because when lines are too long, they become hard to read. That's the main reason why most websites have a fixed width.
eq is used to compare integers use equal '=' instead , example:
if [ 'AAA' = 'ABC' ];
then
echo "the same"
else
echo "not the same"
fi
good luck
The html that you posted should use some <br>
to actually have divs with different heights. Like this:
<div>
<div class="panel">
Line 1<br>
Line 2
</div>
<div class="panel">
Line 1<br>
Line 2<br>
Line 3<br>
Line 4
</div>
<div class="panel">
Line 1
</div>
<div class="panel">
Line 1<br>
Line 2
</div>
</div>
Apart from that, if you want a reference to the div with the max height you can do this:
var highest = null;
var hi = 0;
$(".panel").each(function(){
var h = $(this).height();
if(h > hi){
hi = h;
highest = $(this);
}
});
//highest now contains the div with the highest so lets highlight it
highest.css("background-color", "red");
Add this code in the activity from where you want to exit from the app on pressing back button:
@Override
public void onBackPressed() {
super.onBackPressed();
exitFromApp();
}
private void exitFromApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
You can try this MSDN link
DATEDIFF ( datepart , startdate , enddate )
SELECT DATEDIFF(DAY, '1/1/2011', '3/1/2011')
@Christoph: just adding someting . i dont think so this is a correct way.to logout at both places at the same time.(<a href="/logout" onclick="FB.logout();">Logout</a>
).
Just add id to the anchor tag . <a id='fbLogOut' href="/logout" onclick="FB.logout();">Logout</a>
$(document).ready(function(){
$('#fbLogOut').click(function(e){
e.preventDefault();
FB.logout(function(response) {
// user is now logged out
var url = $(this).attr('href');
window.location= url;
});
});});
Percentage in width works but percentage in height will not work unless you specify a specific height for any parent in the dependent loop...
See this : percentage in height doesn’t work?
There is one edge case where static has a surprising effect(at least it was to me). The C++03 Standard states in 14.6.4.2/1:
For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:
- For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found.
- For the part of the lookup using associated namespaces (3.4.2), only function declarations with external linkage found in either the template definition context or the template instantiation context are found.
...
The below code will call foo(void*)
and not foo(S const &)
as you might expect.
template <typename T>
int b1 (T const & t)
{
foo(t);
}
namespace NS
{
namespace
{
struct S
{
public:
operator void * () const;
};
void foo (void*);
static void foo (S const &); // Not considered 14.6.4.2(b1)
}
}
void b2()
{
NS::S s;
b1 (s);
}
In itself this is probably not that big a deal, but it does highlight that for a fully compliant C++ compiler (i.e. one with support for export
) the static
keyword will still have functionality that is not available in any other way.
// bar.h
export template <typename T>
int b1 (T const & t);
// bar.cc
#include "bar.h"
template <typename T>
int b1 (T const & t)
{
foo(t);
}
// foo.cc
#include "bar.h"
namespace NS
{
namespace
{
struct S
{
};
void foo (S const & s); // Will be found by different TU 'bar.cc'
}
}
void b2()
{
NS::S s;
b1 (s);
}
The only way to ensure that the function in our unnamed namespace will not be found in templates using ADL is to make it static
.
Update for Modern C++
As of C++ '11, members of an unnamed namespace have internal linkage implicitly (3.5/4):
An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage.
But at the same time, 14.6.4.2/1 was updated to remove mention of linkage (this taken from C++ '14):
For a function call where the postfix-expression is a dependent name, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:
For the part of the lookup using unqualified name lookup (3.4.1), only function declarations from the template definition context are found.
For the part of the lookup using associated namespaces (3.4.2), only function declarations found in either the template definition context or the template instantiation context are found.
The result is that this particular difference between static and unnamed namespace members no longer exists.
TL;DR
Use one of these for universal conversion needs
//Java 7 or below
bigDecimal.setScale(0, RoundingMode.DOWN).intValueExact()
//Java 8
bigDecimal.toBigInteger().intValueExact()
Reasoning
The answer depends on what the requirements are and how you answer these question.
BigDecimal
potentially have a non-zero fractional part?BigDecimal
potentially not fit into the Integer
range?If you answered no to the first 2 questions, you could just use BigDecimal.intValueExact()
as others have suggested and let it blow up when something unexpected happens.
If you are not absolutely 100% confident about question number 2, then intValue()
is always the wrong answer.
Making it better
Let's use the following assumptions based on the other answers.
intValueExact()
and auto-boxing doBigDecimal
is larger than the Integer
range because anything else would be crazy unless you have a very specific need for the wrap around that happens when you drop the high-order bits.Given those params, intValueExact()
throws an exception when we don't want it to if our fractional part is non-zero. On the other hand, intValue()
doesn't throw an exception when it should if our BigDecimal
is too large.
To get the best of both worlds, round off the BigDecimal
first, then convert. This also has the benefit of giving you more control over the rounding process.
Spock Groovy Test
void 'test BigDecimal rounding'() {
given:
BigDecimal decimal = new BigDecimal(Integer.MAX_VALUE - 1.99)
BigDecimal hugeDecimal = new BigDecimal(Integer.MAX_VALUE + 1.99)
BigDecimal reallyHuge = new BigDecimal("10000000000000000000000000000000000000000000000")
String decimalAsBigIntString = decimal.toBigInteger().toString()
String hugeDecimalAsBigIntString = hugeDecimal.toBigInteger().toString()
String reallyHugeAsBigIntString = reallyHuge.toBigInteger().toString()
expect: 'decimals that can be truncated within Integer range to do so without exception'
//GOOD: Truncates without exception
'' + decimal.intValue() == decimalAsBigIntString
//BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
// decimal.intValueExact() == decimalAsBigIntString
//GOOD: Truncates without exception
'' + decimal.setScale(0, RoundingMode.DOWN).intValueExact() == decimalAsBigIntString
and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
//BAD: hugeDecimal.intValue() is -2147483648 instead of 2147483648
//'' + hugeDecimal.intValue() == hugeDecimalAsBigIntString
//BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
//'' + hugeDecimal.intValueExact() == hugeDecimalAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + hugeDecimal.setScale(0, RoundingMode.DOWN).intValueExact() == hugeDecimalAsBigIntString
and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
//BAD: hugeDecimal.intValue() is 0
//'' + reallyHuge.intValue() == reallyHugeAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + reallyHuge.intValueExact() == reallyHugeAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + reallyHuge.setScale(0, RoundingMode.DOWN).intValueExact() == reallyHugeAsBigIntString
and: 'if using Java 8, BigInteger has intValueExact() just like BigDecimal'
//decimal.toBigInteger().intValueExact() == decimal.setScale(0, RoundingMode.DOWN).intValueExact()
}
var date = new Date(); // will give you todays date.
// following calls, will let you set new dates.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
var yesterday = new Date();
yesterday.setDate(...date info here);
if(date>yesterday) // will compare dates
My problem was the lack of BindingResult
parameter after my model attribute.
@RequestMapping(method = RequestMethod.POST, value = "/sign-up", consumes = "application/x-www-form-urlencoded")
public ModelAndView registerUser(@Valid @ModelAttribute UserRegistrationInfo userRegistrationInfo
HttpServletRequest httpRequest,
HttpSession httpSession) { ... }
After I added BindingResult
my controller became
@RequestMapping(method = RequestMethod.POST, value = "/sign-up", consumes = "application/x-www-form-urlencoded")
public ModelAndView registerUser(@Valid @ModelAttribute UserRegistrationInfo userRegistrationInfo, BindingResult bindingResult,
HttpServletRequest httpRequest,
HttpSession httpSession) { ..}
Check answer @sashok_bg @sashko_bg Mersi mnogo
$(window).unbind('scroll');
Even though the documentation says it will remove all event handlers if called with no arguments, it is worth giving a try explicitly unbinding it.
It worked if you used single quotes? That doesn't sound right - as far as I know, JavaScript treats single and double quotes the same (unlike some other languages like PHP and C).
I just want to point out to all the people saying, "That's not the point of SecureString
", that many of the people asking this question might be in an application where, for whatever reason, justified or not, they are not particularly concerned about having a temporary copy of the password sit on the heap as a GC-able string, but they have to use an API that only accepts SecureString
objects. So, you have an app where you don't care whether the password is on the heap, maybe it's internal-use only and the password is only there because it's required by the underlying network protocols, and you find that that string where the password is stored cannot be used to e.g. set up a remote PowerShell Runspace -- but there is no easy, straight-forward one-liner to create that SecureString
that you need. It's a minor inconvenience -- but probably worth it to ensure that the applications that really do need SecureString
don't tempt the authors to use System.String
or System.Char[]
intermediaries. :-)
You don't necessarily have to create a Spring project. Almost all Java web applications have he same project structure. In almost every project I create, I automatically add these source folder:
src/main/webapp isn't actually a source folder. The web.xml file under src/main/webapp/WEB-INF will allow you to run your java application on any Java enabled web server (Tomcat, Jetty, etc.). I typically add the Jetty Plugin to my POM (assuming you use Maven), and launch the web app in development using mvn clean jetty:run.
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m');
or
select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');
hard to tell from your example
Easy way
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(makeLabel("my title",x: 0, y: 100, w: 320, h: 30))
}
func makeLabel(title:String, x:CGFloat, y:CGFloat, w:CGFloat, h:CGFloat)->UILabel{
var myLabel : UILabel = UILabel(frame: CGRectMake(x,y,w,h))
myLabel.textAlignment = NSTextAlignment.Right
// inser last char to right
var titlePlus1char = "\(title)1"
myLabel.text = titlePlus1char
var titleSize:Int = count(titlePlus1char)-1
myLabel.textColor = UIColor(red:1.0, green:1.0,blue:1.0,alpha:1.0)
myLabel.backgroundColor = UIColor(red: 214/255, green: 167/255, blue: 0/255,alpha:1.0)
// create myMutable String
var myMutableString = NSMutableAttributedString()
// create myMutable font
myMutableString = NSMutableAttributedString(string: titlePlus1char, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 20)!])
// set margin size
myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 10)!, range: NSRange(location: titleSize,length: 1))
// set last char to alpha 0
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:1.0, green:1.0,blue:1.0,alpha:0), range: NSRange(location: titleSize,length: 1))
myLabel.attributedText = myMutableString
return myLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Found out how to make it work!
I just moved apache2 (the Web Sharing folder) to my desktop.
go to terminal and type "mv /etc/apache2/ /Users/hseungun/Desktop"
actually it says you need authority so
type this "sudo -s" then it'll go to bash-3.2
passwd root
set your password and then "mv /etc/apache2/ /Users/hseungun/Desktop"
try turning on the web sharing, and then start xampp on mac
Login to Server as Admin
Go To Security > Logins > New Login
Step 1:
Login Name : SomeName
Step 2:
Select SQL Server / Windows Authentication.
More Info on, what is the differences between sql server authentication and windows authentication..?
Choose Default DB and Language of your choice
Click OK
Try to connect with the New User Credentials, It will prompt you to change the password. Change and login
OR
Try with query :
USE [master] -- Default DB
GO
CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO
--123456 is the Password And Username is Login User
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO
You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.
ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)
Never compare integer
to strings
in MySQL. If id
is int
, remove the quotes.
I think vscode is using autopep8 to format .py
by default.
"PEP 8 -- Style Guide for Python Code | Python.org"
According to this website, the following may explain why vscode always use 4 spaces.
Use 4 spaces per indentation level.
Here's my solution using json.dump():
def jsonWrite(p, pyobj, ensure_ascii=False, encoding=SYSTEM_ENCODING, **kwargs):
with codecs.open(p, 'wb', 'utf_8') as fileobj:
json.dump(pyobj, fileobj, ensure_ascii=ensure_ascii,encoding=encoding, **kwargs)
where SYSTEM_ENCODING is set to:
locale.setlocale(locale.LC_ALL, '')
SYSTEM_ENCODING = locale.getlocale()[1]
I've posted a script for generating all platform icons for PhoneGap apps from a single SVG icon file. If you have existing bitmaps, I also include some notes that may help you to generate the SVG vectors from an existing bitmap. This won't work for all bitmaps but may for yours.
What I learned was to add "\n" in between the words where you want it to brake into the next line. For example...
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="M-F 9am-5pm \n By Appointment Only" />
The \n between 5pm and By allowed me more control of where I wanted my my next line to begin and end.
The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this
FOR SQL SERVER 2005 and above
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified =(int)cmd.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
return modified;
}
}
FOR previous versions
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified = Convert.ToInt32(cmd.ExecuteScalar());
if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
}
Your Eclipse software suite doesn't support Java 1.8
I played a bit with this problem and at this end I used this:
function getJsonFromUrl() {
return Object.assign(...location.search.substr(1).split("&").map(sliceProperty));
}
Object.assign
to transform a list of object into one object...
to transform an array into a listlocation.search.substr(1).split("&")
to get all parameters as array of properties (foo=bar
)map
walk each properties and split them into an array (either call splitProperty
or sliceProperty
).splitProperty
:
function splitProperty(pair) {
[key, value] = pair.split("=")
return { [key]: decodeURIComponent(value) }
}
=
sliceProperty
:
function sliceProperty(pair) {
const position = pair.indexOf("="),
key = pair.slice(0, position),
value = pair.slice(position + 1, pair.length);
return { [key]: decodeURIComponent(value) }
}
=
, key and valueI think splitProperty
is prettier but sliceProperty
is faster. Run JsPerf for more information.
Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.
So, it depends on how you've decorated your class as to how to keep a member from serializing:
[DataContract]
, then remove the [DataMember]
for the property.[Serializable]
, then add [NonSerialized]
in front of the field for the property.[IgnoreDataMember]
to the property.Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
On mac Big Sur and MySQL 5.7, I needed to stop/start with:
sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
and
sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
This answer came from https://coolestguidesontheplanet.com/start-stop-mysql-from-the-command-line-terminal-osx-linux/
You will need to get the textbox via javascript when moving the mouse over it and change its type
to text
. And when moving it out, you will want to change it back to password
. No chance of doing this in pure CSS.
HTML:
<input type="password" name="password" id="myPassword" size="30" />
<img src="theicon" onmouseover="mouseoverPass();" onmouseout="mouseoutPass();" />
JS:
function mouseoverPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "text";
}
function mouseoutPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "password";
}
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
in exemple if you want to compile sources but have objects in an different directory :
You need to do :
gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...
but with most of macros the result will be all objects followed by all sources, like :
gcc -c -o <all OBJ path> <all SRC path>
so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(
the solution is to use these special macros
$@ $<
this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)
$(OBJ):$(SRC)
gcc -c -o $@ $< $(HEADERS) $(FLAGS)
it means :
$@ = $(OBJ)
$< = $(SRC)
but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC
Select Tools > Preferences > Database / Advanced
There is an input field for Sql Array Fetch Size but it only allows setting a max of 500 rows.
You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL
If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is
<xs:sequence>
<xs:element.../>
</xs:sequence>
The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:
<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1" ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2" ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3" ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>
Solution:
Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!
First thing replace "xs:sequence" with "<xs:all>"
Now,You need to make some changes where you are Referring the element from,
There go to:
<xs:annotation>
<xs:appinfo>
<b:recordinfo structure="delimited" field.........Biztalk/2003">
***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38"
Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">
This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).
Hope it helps you, for I spent almost 20 hrs on this.
Good Luck
I fixed the same error by doing a Ruby reinstall via rvm:
rvm reinstall 1.9.3
This line:
myForm.file.$setValidity("myForm.file.$error.size", false);
Should be
$scope.myForm.file.$setValidity("size", false);
For those running pre-java7, named groups are supported by joni (Java port of the Oniguruma regexp library). Documentation is sparse, but it has worked well for us.
Binaries are available via Maven (http://repository.codehaus.org/org/jruby/joni/joni/).
If you want only the scheme and authority part of the request (protocol, host and port) use
Request.Url.GetLeftPart(UriPartial.Authority)
With argparse you could do:
parser.argparse.ArgumentParser()
#parser.add_args here
#sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
Perhaps 0
or '\u0000'
would do?
The easiest way is this.
var items = Array(523,3452,334,31, 5346);
var replaceWhat = 3452, replaceWith = 1010;
if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);
console.log(items);
>>> (5) [523, 1010, 334, 31, 5346]
To get difference in months (both start and end inclusive), irrespective of dates:
DateTime start = new DateTime(2013, 1, 1);
DateTime end = new DateTime(2014, 2, 1);
var diffMonths = (end.Month + end.Year * 12) - (start.Month + start.Year * 12);
There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code
var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(path, ImageFormat.Png);
}
CSS can do that with background-size: cover;
But to be more detailed and support more browsers...
Use aspect ratio like this:
aspectRatio = $bg.width() / $bg.height();
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
For int64_t
type:
#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);
for uint64_t
type:
#include <inttypes.h>
uint64_t t;
printf("%" PRIu64 "\n", t);
you can also use PRIx64
to print in hexadecimal.
cppreference.com has a full listing of available macros for all types including intptr_t
(PRIxPTR
). There are separate macros for scanf, like SCNd64
.
A typical definition of PRIu16 would be "hu"
, so implicit string-constant concatenation happens at compile time.
For your code to be fully portable, you must use PRId32
and so on for printing int32_t
, and "%d"
or similar for printing int
.
$img_file='http://www.somedomain.com/someimage.jpg'
$img_file=file_get_contents($img_file);
$file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';
$file_handler=fopen($file_loc,'w');
if(fwrite($file_handler,$img_file)==false){
echo 'error';
}
fclose($file_handler);
Apache Commons Lang has StringUtils.isEmpty(String str)
method which returns true if argument is empty or null
To be more semantically correct and answer the OPs orginal question about aligning them side by side I would use this:
HTML
<div class="items">
<figure>
<img src="hello.png" width="100px" height="100px">
<figcaption>Caption 1</figcaption>
</figure>
<figure>
<img src="hi.png" width="100px" height="100px">
<figcaption>Caption 2</figcaption>
</figure></div>
CSS
.items{
text-align:center;
margin:50px auto;}
.items figure{
margin:0px 20px;
display:inline-block;
text-decoration:none;
color:black;}
brew
Show current version
$ php -v
Change to different version
(eg. changing from 5.5.x to version 7.0.latest) :
$ brew unlink php55
$ brew install php70
SELECT employee_id,department_id AS department
FROM employees
order by department
SELECT employee_id,department_id AS "department"
FROM employees
order by department
--error on oracle--
so better to use AS without double quotation if you use ORDER BY clause
I think I got it. I have to use org.w3c.dom.Element
explicitly. I had a different Element field too.
Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult?
@SqlResultSetMapping(
name="groupDetailsMapping",
classes={
@ConstructorResult(
targetClass=GroupDetails.class,
columns={
@ColumnResult(name="GROUP_ID"),
@ColumnResult(name="USER_ID")
}
)
}
)
@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
and use following in repository interface:
GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);
According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using @NamedNativeQuery
, @SqlResultSetMapping
and @ConstructorResult
you should be able to achieve that behaviour
** Problem Solved ** // Changed to delegate() method to use delegation from the body
$("body").delegate("#boundOnPageLoaded", "click", function(){
alert("Delegated Button Clicked")
});
For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.
public static string[] GetStringInBetween(string strBegin,
string strEnd, string strSource,
bool includeBegin, bool includeEnd)
{
string[] result ={ "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin);
if (iIndexOfBegin != -1)
{
// include the Begin string if desired
if (includeBegin)
iIndexOfBegin -= strBegin.Length;
strSource = strSource.Substring(iIndexOfBegin
+ strBegin.Length);
int iEnd = strSource.IndexOf(strEnd);
if (iEnd != -1)
{
// include the End string if desired
if (includeEnd)
iEnd += strEnd.Length;
result[0] = strSource.Substring(0, iEnd);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd
+ strEnd.Length);
}
}
else
// stay where we are
result[1] = strSource;
return result;
}
In javascript (uses jQuery):
function vimeoLoadingThumb(id){
var url = "http://vimeo.com/api/v2/video/" + id + ".json?callback=showThumb";
var id_img = "#vimeo-" + id;
var script = document.createElement( 'script' );
script.src = url;
$(id_img).before(script);
}
function showThumb(data){
var id_img = "#vimeo-" + data[0].id;
$(id_img).attr('src',data[0].thumbnail_medium);
}
To display it :
<img id="vimeo-{{ video.id_video }}" src="" alt="{{ video.title }}" />
<script type="text/javascript">
vimeoLoadingThumb({{ video.id_video }});
</script>
with the intl extension in PHP 5.3+, you can use the NumberFormatter class:
$amount = '12345.67';
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
which prints :
UK: €12,345.67
DE: 12.345,67 €
http://www.kernel.org/pub/software/scm/git/docs/git-revert.html
using git revert <commit>
will create a new commit that reverts the one you dont want to have.
You can specify a list of commits to revert.
An alternative: http://git-scm.com/docs/git-reset
git reset
will reset your copy to the commit you want.
Editing library dependencies through the GUI is not advisable as that doesn't write those changes to your build.gradle file. So your project will not build from the command-line. We should edit the build.gradle file directly as follows.
For instance, given to following structure:
MyProject/
We can identify three projects. Gradle will reference them with the following names:
The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:
dependencies {
compile project(':libraries:lib1')
}
I believe python arrays just admit values. So convert it to list:
kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()
Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.
Also you can try to use
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.
The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?
Require all granted
is only in 2.4, but Allow all ...
stops working in 2.4, and we want to be able to rollout a config that works in both.
The only solution I found, which I am not sure is the proper one, is to use:
# backwards compatibility with apache 2.2
Order allow,deny
Allow from all
# forward compatibility with apache 2.4
Require all granted
Satisfy Any
This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...
See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.
I prefer to optimize the one year group selection like so:
SELECT COUNT(*)
FROM stats
WHERE record_date >= :year
AND record_date < :year + INTERVAL 1 YEAR;
This way you can just bind the year in once, e.g. '2009'
, with a named parameter and don't need to worry about adding '-01-01'
or passing in '2010'
separately.
Also, as presumably we are just counting rows and id
is never NULL
, I prefer COUNT(*)
to COUNT(id)
.
Basically there's three things you can do
I've just writen an answer to a very similar answer here where I explain how you can disable UAC since Windows 8.
There also other ways to use the composer autoload features. Ways that can be useful to load packages without namespaces or packages that come with a custom autoload function.
For example if you want to include a single file that contains an autoload function as well you can use the "files" directive as follows:
"autoload": {
"psr-0": {
"": "src/",
"SymfonyStandard": "app/"
},
"files": ["vendor/wordnik/wordnik-php/wordnik/Swagger.php"]
},
And inside the Swagger.php
file we got:
function swagger_autoloader($className) {
$currentDir = dirname(__FILE__);
if (file_exists($currentDir . '/' . $className . '.php')) {
include $currentDir . '/' . $className . '.php';
} elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
include $currentDir . '/models/' . $className . '.php';
}
}
spl_autoload_register('swagger_autoloader');
https://getcomposer.org/doc/04-schema.md#files
Otherwise you may want to use a classmap reference:
{
"autoload": {
"classmap": ["src/", "lib/", "Something.php"]
}
}
https://getcomposer.org/doc/04-schema.md#classmap
Note: during your tests remember to launch the composer dump-autoload
command or you won't see any change!
./composer.phar dump-autoload
Happy autoloading =)
This will work for most of the website names :
SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....
PowerShell's select-string is similar, it's not the same options and semantics, but it's still powerful.
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
You can also use substring replacement to test for the presence of a substring. Here I remove quotes to create PATH_NQ, then I remove "c:\mydir" from the PATH_NQ and compare it to the original to see if anything changed:
set PATH_NQ=%PATH:"=%
if not "%PATH_NQ%"=="%PATH_NQ:c:\mydir=%" goto already_in_path
set PATH=%PATH%;c:\mydir
:already_in_path
In a couple of lines, Cygwin and PowerShell are different tools however if you have Cygwin installed you can run the Cygwin executables within a PowerShell session. I've gotten so used to PowerShell that now I no longer use grep, sort, awk, etc. There are pretty much built-in alternatives in PowerShell, and if not you can find a cmdlet out there.
The main tool I find myself using is ssh.exe, but within a PowerShell session.
It works great.
When rewriting the html is allowed, you can nest <ul>
s within the <ul>
and just let the inner <li>
s display as inline-block. This would also semantically make sense IMHO, as the grouping also is reflected within the html.
<ul>
<li>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</li>
<li>
<ul>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</li>
</ul>
li li { display:inline-block; }
$(function() { $('img').attr('src', 'http://phrogz.net/tmp/alphaball.png'); });
_x000D_
h3 {_x000D_
border-bottom: 1px solid #ccc;_x000D_
font-family: sans-serif;_x000D_
font-weight: bold;_x000D_
}_x000D_
ul {_x000D_
margin: 0.5em auto;_x000D_
list-style-type: none;_x000D_
}_x000D_
li li {_x000D_
text-align: center;_x000D_
display: inline-block;_x000D_
padding: 0.1em 1em;_x000D_
}_x000D_
img {_x000D_
width: 64px;_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h3>Features</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<ul>_x000D_
<li><img />Smells Good</li>_x000D_
<li><img />Tastes Great</li>_x000D_
<li><img />Delicious</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>_x000D_
<ul>_x000D_
<li><img />Wholesome</li>_x000D_
<li><img />Eats Children</li>_x000D_
<li><img />Yo' Mama</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
Here is a solution using functions plot()
, polygon()
and lines()
.
set.seed(1234)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
plot(df$x, df$F, ylim = c(0,4), type = "l")
#make polygon where coordinates start with lower limit and
# then upper limit in reverse order
polygon(c(df$x,rev(df$x)),c(df$L,rev(df$U)),col = "grey75", border = FALSE)
lines(df$x, df$F, lwd = 2)
#add red lines on borders of polygon
lines(df$x, df$U, col="red",lty=2)
lines(df$x, df$L, col="red",lty=2)
Now use example data provided by OP in another question:
Lower <- c(0.418116841, 0.391011834, 0.393297710,
0.366144073,0.569956636,0.224775521,0.599166016,0.512269587,
0.531378573, 0.311448219, 0.392045751,0.153614913, 0.366684097,
0.161100849,0.700274810,0.629714150, 0.661641288, 0.533404093,
0.412427559, 0.432905333, 0.525306427,0.224292061,
0.28893064,0.099543648, 0.342995605,0.086973739,0.289030388,
0.081230826,0.164505624, -0.031290586,0.148383474,0.070517523,0.009686605,
-0.052703529,0.475924192,0.253382210, 0.354011010,0.130295355,0.102253218,
0.446598823,0.548330752,0.393985810,0.481691632,0.111811248,0.339626541,
0.267831909,0.133460254,0.347996621,0.412472322,0.133671128,0.178969601,0.484070587,
0.335833224,0.037258467, 0.141312363,0.361392799,0.129791998,
0.283759439,0.333893418,0.569533076,0.385258093,0.356201955,0.481816148,
0.531282473,0.273126565,0.267815691,0.138127486,0.008865700,0.018118398,0.080143484,
0.117861634,0.073697418,0.230002398,0.105855042,0.262367348,0.217799352,0.289108011,
0.161271889,0.219663224,0.306117717,0.538088622,0.320711912,0.264395149,0.396061543,
0.397350946,0.151726970,0.048650180,0.131914718,0.076629840,0.425849394,
0.068692279,0.155144797,0.137939059,0.301912657,-0.071415593,-0.030141781,0.119450922,
0.312927614,0.231345972)
Upper.limit <- c(0.6446223,0.6177311, 0.6034427, 0.5726503,
0.7644718, 0.4585430, 0.8205418, 0.7154043,0.7370033,
0.5285199, 0.5973728, 0.3764209, 0.5818298,
0.3960867,0.8972357, 0.8370151, 0.8359921, 0.7449118,
0.6152879, 0.6200704, 0.7041068, 0.4541011, 0.5222653,
0.3472364, 0.5956551, 0.3068065, 0.5112895, 0.3081448,
0.3745473, 0.1931089, 0.3890704, 0.3031025, 0.2472591,
0.1976092, 0.6906118, 0.4736644, 0.5770463, 0.3528607,
0.3307651, 0.6681629, 0.7476231, 0.5959025, 0.7128883,
0.3451623, 0.5609742, 0.4739216, 0.3694883, 0.5609220,
0.6343219, 0.3647751, 0.4247147, 0.6996334, 0.5562876,
0.2586490, 0.3750040, 0.5922248, 0.3626322, 0.5243285,
0.5548211, 0.7409648, 0.5820070, 0.5530232, 0.6863703,
0.7206998, 0.4952387, 0.4993264, 0.3527727, 0.2203694,
0.2583149, 0.3035342, 0.3462009, 0.3003602, 0.4506054,
0.3359478, 0.4834151, 0.4391330, 0.5273411, 0.3947622,
0.4133769, 0.5288060, 0.7492071, 0.5381701, 0.4825456,
0.6121942, 0.6192227, 0.3784870, 0.2574025, 0.3704140,
0.2945623, 0.6532694, 0.2697202, 0.3652230, 0.3696383,
0.5268808, 0.1545602, 0.2221450, 0.3553377, 0.5204076,
0.3550094)
Fitted.values<- c(0.53136955, 0.50437146, 0.49837019,
0.46939721, 0.66721423, 0.34165926, 0.70985388, 0.61383696,
0.63419092, 0.41998407, 0.49470927, 0.26501789, 0.47425695,
0.27859380, 0.79875525, 0.73336461, 0.74881668, 0.63915795,
0.51385774, 0.52648789, 0.61470661, 0.33919656, 0.40559797,
0.22339000, 0.46932536, 0.19689011, 0.40015996, 0.19468781,
0.26952645, 0.08090917, 0.26872696, 0.18680999, 0.12847285,
0.07245286, 0.58326799, 0.36352329, 0.46552867, 0.24157804,
0.21650915, 0.55738088, 0.64797691, 0.49494416, 0.59728999,
0.22848680, 0.45030036, 0.37087676, 0.25147426, 0.45445930,
0.52339711, 0.24922310, 0.30184215, 0.59185198, 0.44606040,
0.14795374, 0.25815819, 0.47680880, 0.24621212, 0.40404398,
0.44435727, 0.65524894, 0.48363255, 0.45461258, 0.58409323,
0.62599114, 0.38418264, 0.38357103, 0.24545011, 0.11461756,
0.13821664, 0.19183886, 0.23203127, 0.18702881, 0.34030391,
0.22090140, 0.37289121, 0.32846615, 0.40822456, 0.27801706,
0.31652008, 0.41746184, 0.64364785, 0.42944100, 0.37347037,
0.50412786, 0.50828681, 0.26510696, 0.15302635, 0.25116438,
0.18559609, 0.53955941, 0.16920626, 0.26018389, 0.25378867,
0.41439675, 0.04157232, 0.09600163, 0.23739430, 0.41666762,
0.29317767)
Assemble into a data frame (no x provided, so using indices)
df2 <- data.frame(x=seq(length(Fitted.values)),
fit=Fitted.values,lwr=Lower,upr=Upper.limit)
plot(fit~x,data=df2,ylim=range(c(df2$lwr,df2$upr)))
#make polygon where coordinates start with lower limit and then upper limit in reverse order
with(df2,polygon(c(x,rev(x)),c(lwr,rev(upr)),col = "grey75", border = FALSE))
matlines(df2[,1],df2[,-1],
lwd=c(2,1,1),
lty=1,
col=c("black","red","red"))
Here's a working example to send plain text and HTML emails from Python using smtplib
along with the CC and BCC options.
https://varunver.wordpress.com/2017/01/26/python-smtplib-send-plaintext-and-html-emails/
#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(params, type_):
email_subject = params['email_subject']
email_from = "[email protected]"
email_to = params['email_to']
email_cc = params.get('email_cc')
email_bcc = params.get('email_bcc')
email_body = params['email_body']
msg = MIMEMultipart('alternative')
msg['To'] = email_to
msg['CC'] = email_cc
msg['Subject'] = email_subject
mt_html = MIMEText(email_body, type_)
msg.attach(mt_html)
server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
server.set_debuglevel(1)
toaddrs = [email_to] + [email_cc] + [email_bcc]
server.sendmail(email_from, toaddrs, msg.as_string())
server.quit()
# Calling the mailer functions
params = {
'email_to': '[email protected]',
'email_cc': '[email protected]',
'email_bcc': '[email protected]',
'email_subject': 'Test message from python library',
'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
send_mail(params, t)
There are many ways to do this:
Go to current File once:
Visual Studio 2013
VS 13 has it's own shortcut to do this: Ctrl+\, S (Press Ctrl + \, Release both keys, Press the S key)
You can edit this default shortcut, if you are searching for SolutionExplorer.SyncWithActiveDocument
in your Keyboard Settings
(Tools->Options->Enviornment->Keyboard)
In addition there is also a new icon in the Solution Explorer, more about this here.
Visual Studio 2012
If you use VS 2012, there is a great plugin to add this new functionality from VS2013 to VS2012: . The default shortcut is strg + alt + ü. I think this one is the best, as navigating to the solution explorer is mapped to strg + ü.
Resharper
If you use Resharper try Shift+Alt+L
This is a nice mapping as you can use Strg+Alt+L for navigating to the solution explorer
Track current file all the time:
Visual Studio >= 2012:
If you like to track your current file in the solution explorer all the time, you can use the solution from the accepted answer (Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer), but I think this can get very annoying in large projects.
This is an old thread, but I thought I should post my solution. I faced the same problem recently and the way I solved it is by following a three-step approach as outlined below which is very simple without any complex CSS.
(NOTE : Of course, for modern browsers, using the values of table or table-row or table-cell for display CSS attribute would solve the problem. But the approach I used will work equally well in modern and older browsers since it does not use these values for display CSS attribute.)
3-STEP SIMPLE APPROACH
For table with divs only so you get cells and rows just like in a table element use the following approach.
.table
class).row
class).cell
class).table {display:block; }_x000D_
.row { display:block;}_x000D_
.cell {display:inline-block;}
_x000D_
<h2>Table below using table element</h2>_x000D_
<table cellspacing="0" >_x000D_
<tr>_x000D_
<td>Mike</td>_x000D_
<td>36 years</td>_x000D_
<td>Architect</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sunil</td>_x000D_
<td>45 years</td>_x000D_
<td>Vice President aas</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jason</td>_x000D_
<td>27 years</td>_x000D_
<td>Junior Developer</td>_x000D_
</tr>_x000D_
</table>_x000D_
<h2>Table below is using Divs only</h2>_x000D_
<div class="table">_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Mike_x000D_
</div>_x000D_
<div class="cell">_x000D_
36 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Architect_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Sunil_x000D_
</div>_x000D_
<div class="cell">_x000D_
45 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Vice President_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Jason_x000D_
</div>_x000D_
<div class="cell">_x000D_
27 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Junior Developer_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
UPDATE 1
To get around the effect of same width not being maintained across all cells of a column as mentioned by thatslch
in a comment, one could adopt either of the two approaches below.
Specify a width for cell
class
cell {display:inline-block; width:340px;}
Use CSS of modern browsers as below.
.table {display:table; } .row { display:table-row;} .cell {display:table-cell;}
I would go with netcat too , but since you can't use it , here is an alternative : netcat :). You can find netcat implemented in three languages ( python/ruby/perl ) . All you need to do is install the interpreters for the language you choose . Surely , that won't be viewed as a hacking tool .
Here are the links :
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
You could use the .attr()
function:
$(this).attr('data-fullText')
or if you lowercase the attribute name:
data-fulltext="This is a span element"
then you could use the .data()
function:
$(this).data('fulltext')
The .data()
function expects and works only with lowercase attribute names.
Use the below snippet it will be helpfull.
string POCpath = @"G:\Althaf\abc.xlsx";
string POCConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + POCpath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection POCcon = new OleDbConnection(POCConnection);
OleDbCommand POCcommand = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter POCCommand = new OleDbDataAdapter("select * from [Sheet1$] ", POCcon);
POCCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
if your tmp folder is relative to the directory where your code is running remove the /
in front of /tmp
.
So you just have tmp/test.jpg
in your code. This worked for me in a similar situation.
This error would occur if any of the following variables were actually strings or null instead of arrays, in which case accessing them with an array syntax $var[$i]
would be like trying to access a specific character in a string:
$catagory
$task
$fullText
$dueDate
$empId
In short, everything in your insert query.
Perhaps the $catagory
variable is misspelled?
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
There exist special libraries to do just that. (Plus wrappers for python)
netCDF4 Python interface: http://www.unidata.ucar.edu/software/netcdf/software.html#Python
hope this helps
Try this: It will open the default mail directly.
<a href="mailto:[email protected]"><img src="ICON2.png"></a>
I have occurred the same error look following example-
async.waterfall([function(waterCB) {
waterCB(null);
}, function(**inputArray**, waterCB) {
waterCB(null);
}], function(waterErr, waterResult) {
console.log('Done');
});
In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.
Cheak your function parameters Below are a correct example.
async.waterfall([function(waterCB) {
waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
waterCB(null);
}], function(waterErr, waterResult) {
console.log('Done');
});
Thanks
a[len(a):]
- This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)]
it will get you the beginning to whatever is len(a)
.
In El-Capitan config.xml can not be found at
/var/lib/jenkins/
Its available in
~/.jenkins
then after that as other mentioned open the config.xml file and make the following changes
In this replace <useSecurity>true</useSecurity>
with <useSecurity>false</useSecurity>
Remove <authorizationStrategy>
and <securityRealm>
Save it and restart the jenkins(sudo service jenkins restart)
(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)
Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:
iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT
Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState
to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}?
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView
:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
@JavisPerez -- Is there any way to compress that image to 150kb at least? Is that possible? What ImageMagick options can I use?
See the following links where there is an option in ImageMagick to specify the desired output file size for writing to JPG files.
http://www.imagemagick.org/Usage/formats/#jpg_write http://www.imagemagick.org/script/command-line-options.php#define
-define jpeg:extent={size}
As of IM v6.5.8-2 you can specify a maximum output filesize for the JPEG image. The size is specified with a suffix. For example "400kb".
convert image.jpg -define jpeg:extent=150kb result.jpg
You will lose some quality by decompressing and recompressing in addition to any loss due to lowering -quality value from the input.
function invertArray(array,arrayWidth,arrayHeight) {
var newArray = [];
for (x=0;x<arrayWidth;x++) {
newArray[x] = [];
for (y=0;y<arrayHeight;y++) {
newArray[x][y] = array[y][x];
}
}
return newArray;
}
For uploading Form-Encoded POST requests, I recommend using the FormData object.
Example code:
var params = {
userName: '[email protected]',
password: 'Password!',
grant_type: 'password'
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
var request = {
method: 'POST',
headers: headers,
body: formData
};
fetch(url, request);
Change your gradle version or update it
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
alt+enter and choose "replace with specific version".
Here's a blog post describing the creation of an IsInteger
UDF.
Basically, it recommends adding '.e0'
to the value and using IsNumeric
. In this way, anything that already had a decimal point now has two decimal points, causing IsNumeric
to be false, and anything already expressed in scientific notation is invalidated by the e0
.
Did you read clang
documentation ? You're probably looking for -emit-llvm
.
Thank you for your responses. Turns out my problem was a database issue with duplicate entries, not with my logic. A quick table sync fixed that and the SUM feature worked as expected. This is all still useful knowledge for the SUM feature and is worth reading if you are having trouble using it.
You should try dplyr package
library(dplyr)
a <- data.frame(A = c(1, 2, 3, 4),
B = c(11, 12, 13, 14))
system.time({
for (i in 50:1000) {
b <- data.frame(A = i, B = i * i)
a <- bind_rows(a, b)
}
})
Output
user system elapsed
0.25 0.00 0.25
In contrast with using rbind function
a <- data.frame(A = c(1, 2, 3, 4),
B = c(11, 12, 13, 14))
system.time({
for (i in 50:1000) {
b <- data.frame(A = i, B = i * i)
a <- rbind(a, b)
}
})
Output
user system elapsed
0.49 0.00 0.49
There is some performance gain.
getcwd();
or
dirname(__FILE__);
or (PHP5)
basename(__DIR__)
http://php.net/manual/en/function.getcwd.php
http://php.net/manual/en/function.dirname.php
You can use basename()
to get the trailing part of the path :)
In your case, I'd say you are most likely looking to use getcwd()
, dirname(__FILE__)
is more useful when you have a file that needs to include another library and is included in another library.
Eg:
main.php
libs/common.php
libs/images/editor.php
In your common.php
you need to use functions in editor.php
, so you use
common.php
:
require_once dirname(__FILE__) . '/images/editor.php';
main.php
:
require_once libs/common.php
That way when common.php is require'd
in main.php
, the call of require_once
in common.php
will correctly includes editor.php
in images/editor.php
instead of trying to look in current directory where main.php
is run.
Expanding on @gecco 's answer, the following is an example that'll show you the difference:
def foo(**kwargs):
for entry in kwargs.items():
print("Key: {}, value: {}".format(entry[0], entry[1]))
# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})
# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")
Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails
Using .insertAdjacentHTML()
preserves event listeners, and is supported by all major browsers. It's a simple one-line replacement for .innerHTML
.
var html_to_insert = "<p>New paragraph</p>";
// with .innerHTML, destroys event listeners
document.getElementById('mydiv').innerHTML += html_to_insert;
// with .insertAdjacentHTML, preserves event listeners
document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert);
The 'beforeend'
argument specifies where in the element to insert the HTML content. Options are 'beforebegin'
, 'afterbegin'
, 'beforeend'
, and 'afterend'
. Their corresponding locations are:
<!-- beforebegin -->
<div id="mydiv">
<!-- afterbegin -->
<p>Existing content in #mydiv</p>
<!-- beforeend -->
</div>
<!-- afterend -->
Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.
In addition to global "editor.rulers"
setting, it's also possible to set this on a per-language level.
For example, style guides for Python projects often specify either 79 or 120 characters vs. Git commit messages should be no longer than 50 characters.
So in your settings.json
, you'd put:
"[git-commit]": {"editor.rulers": [50]},
"[python]": {
"editor.rulers": [
79,
120
]
}
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}
The correct answer is
Options -Indexes
You must have been thinking of
AllowOverride All
https://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
Combining @Joachim's with the above, you could use
next(iter(my_list[index:index+1]), default)
Examples:
next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11
Or, maybe more clear, but without the len
my_list[index] if my_list[index:index + 1] else default
It's possible that the error didn't occur in the dot product, but after. For example try this
a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c
np.dot(a,b) will be fine; however np.dot(a, b) * c is clearly wrong (12x1 X 1x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give you
ValueError: operands could not be broadcast together with shapes (12,1) (1,5)
The error is misleading; however there is an issue on that line.
From Java Tutorial - Restrictions on Generics:
Cannot Create Instances of Type Parameters
You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
As a workaround, you can create an object of a type parameter through reflection:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);
The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.
It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>
Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.
Sometimes the symbol used as a placeholder %
is not the same if you execute a query from VB as when you execute it from MS SQL / Access. Try changing your placeholder symbol from %
to *
. That might work.
However, if you debug and want to copy your SQL string directly in MS SQL or Access to test it, you may have to change the symbol back to %
in MS SQL or Access in order to actually return values.
Hope this helps
After a power blackout, I ran into the database disk image is malformed error and the suggested reindex nodes command did not fix all issues due to violated constraints. Also the procedure described in http://mail-archives.apache.org/mod_mbox/subversion-users/201111.mbox/%[email protected]%3E did not resolve the problem.
Solution in my case:
This may be useful, if your original svn checkout contains many modified or unversioned files and you don't want to switch to a fresh svn checkout.
Try This :
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/**
* Method to check whether external media available and writable. This is
* adapted from
* http://developer.android.com/guide/topics/data/data-storage.html
* #filesExternal
*/
private void checkExternalMedia() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable=" + mExternalStorageAvailable
+ " writable=" + mExternalStorageWriteable);
}
/**
* Method to write ascii text characters to file on SD card. Note that you
* must add a WRITE_EXTERNAL_STORAGE permission to the manifest file or this
* method will throw a FileNotFound Exception because you won't have write
* permission.
*/
private void writeToSDFile() {
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data-
// storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: " + root);
// See
// http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you"
+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to " + file);
}
/**
* Method to read in a text file placed in the res/raw directory of the
* application. The method reads in all lines of the file sequentially.
*/
private void readRaw() {
tv.append("\nData read from res/raw/textfile.txt:");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer
// size
// More efficient (less readable) implementation of above is the
// composite expression
/*
* BufferedReader br = new BufferedReader(new InputStreamReader(
* this.getResources().openRawResource(R.raw.textfile)), 8192);
*/
try {
String test;
while (true) {
test = br.readLine();
// readLine() returns null if no more lines in the file
if (test == null) break;
tv.append("\n" + " " + test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
To synthesize the excellent original answers from @adardesign, @adswebwork and @AnkitVishwakarma, and comments from @Bdoserror, @Retsam, @seanf, and @torek, with additional documentation links and concise aliases...
Basic Commands
To reset a file that is assume-unchanged back to normal:
git update-index --no-assume-unchanged <file>
To list all files that are assume-unchanged:
git ls-files -v | grep '^[a-z]' | cut -c3-
To reset all assume-unchanged files back to normal:
git ls-files -v | grep '^[a-z]' | cut -c3- | xargs git update-index --no-assume-unchanged --
Note: This command which has been listed elsewhere does not appear to reset all assume-unchanged files any longer (I believe it used to and previously listed it as a solution):
git update-index --really-refresh
Shortcuts
To make these common tasks easy to execute in git, add/update the following alias section to .gitconfig
for your user (e.g. ~/.gitconfig
on a *nix or macOS system):
[alias]
hide = update-index --assume-unchanged
unhide = update-index --no-assume-unchanged
unhide-all = ! git ls-files -v | grep '^[a-z]' | cut -c3- | xargs git unhide --
hidden = ! git ls-files -v | grep '^[a-z]' | cut -c3-
Technically possible. You would probably reference employees_ce in deductions and employees_sn. But why don't you merge employees_sn and employees_ce? I see no reason why you have two table. No one to many relationship. And (not in this example) many columns.
If you do two references for one column, an employee must have an entry in both tables.
clean
is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install
tells Maven to do the clean
phase in each module before running the install
phase for each module.
What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.
You can use a simpler pre-processor trick if you are willing to list your enum
entries in an external file.
/* file: errors.def */
/* syntax: ERROR_DEF(name, value) */
ERROR_DEF(ErrorA, 0x1)
ERROR_DEF(ErrorB, 0x2)
ERROR_DEF(ErrorC, 0x4)
Then in a source file, you treat the file like an include file, but you define what you want the ERROR_DEF
to do.
enum Errors {
#define ERROR_DEF(x,y) x = y,
#include "errors.def"
#undef ERROR_DEF
};
static inline std::ostream & operator << (std::ostream &o, Errors e) {
switch (e) {
#define ERROR_DEF(x,y) case y: return o << #x"[" << y << "]";
#include "errors.def"
#undef ERROR_DEF
default: return o << "unknown[" << e << "]";
}
}
If you use some source browsing tool (like cscope), you'll have to let it know about the external file.
var accounting = [];
var employees = {};
for(var i in someData) {
var item = someData[i];
accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
employees.accounting = accounting;
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
In terms of the XML format for log4net, you need not worry about ex.ToString() for the logs. Simply pass the exception object itself and log4net does the rest do give you all of the details in its pre-configured XML format. The only thing I run into on occasion is new line formatting, but that's when I'm reading the files raw. Otherwise parsing the XML works great.
Based on previous answers this has worked for me with Python 3.7
from urllib.request import Request, urlopen
req = Request('Url_Link', headers={'User-Agent': 'XYZ/3.0'})
webpage = urlopen(req, timeout=10).read()
print(webpage)
Use:
echo %time% & dir & echo %time%
This is, from memory, equivalent to the semi-colon separator in bash
and other UNIXy shells.
There's also &&
(or ||
) which only executes the second command if the first succeeded (or failed), but the single ampersand &
is what you're looking for here.
That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.
You can get round this by turning on delayed expansion:
pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85
That's needed from the command line. If you're doing this inside a script, you can just use setlocal
:
@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
How does it send the file internally?
The format is called multipart/form-data
, as asked at: What does enctype='multipart/form-data' mean?
I'm going to:
There are three possibilities for enctype
:
x-www-urlencoded
multipart/form-data
(spec points to RFC2388)text-plain
. This is "not reliably interpretable by computer", so it should never be used in production, and we will not look further into it.Once you see an example of each method, it becomes obvious how they work, and when you should use each one.
You can produce examples using:
nc -l
or an ECHO server: HTTP test server accepting GET/POST requestsSave the form to a minimal .html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>upload</title>
</head>
<body>
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text1" value="text default">
<p><input type="text" name="text2" value="aωb">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><input type="file" name="file3">
<p><button type="submit">Submit</button>
</form>
</body>
</html>
We set the default text value to aωb
, which means a?b
because ?
is U+03C9
, which are the bytes 61 CF 89 62
in UTF-8.
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
# Binary file containing 4 bytes: 'a', 1, 2 and 'b'.
printf 'a\xCF\x89b' > binary
Run our little echo server:
while true; do printf '' | nc -l 8000 localhost; done
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received.
Tested on: Ubuntu 14.04.3, nc
BSD 1.105, Firefox 40.
Firefox sent:
POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
Content-Length: 834
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text1"
text default
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text2"
a?b
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file3"; filename="binary"
Content-Type: application/octet-stream
a?b
-----------------------------735323031399963166993862150--
For the binary file and text field, the bytes 61 CF 89 62
(a?b
in UTF-8) are sent literally. You could verify that with nc -l localhost 8000 | hd
, which says that the bytes:
61 CF 89 62
were sent (61
== 'a' and 62
== 'b').
Therefore it is clear that:
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
sets the content type to multipart/form-data
and says that the fields are separated by the given boundary
string.
But note that the:
boundary=---------------------------735323031399963166993862150
has two less dadhes --
than the actual barrier
-----------------------------735323031399963166993862150
This is because the standard requires the boundary to start with two dashes --
. The other dashes appear to be just how Firefox chose to implement the arbitrary boundary. RFC 7578 clearly mentions that those two leading dashes --
are required:
4.1. "Boundary" Parameter of multipart/form-data
As with other multipart types, the parts are delimited with a boundary delimiter, constructed using CRLF, "--", and the value of the "boundary" parameter.
every field gets some sub headers before its data: Content-Disposition: form-data;
, the field name
, the filename
, followed by the data.
The server reads the data until the next boundary string. The browser must choose a boundary that will not appear in any of the fields, so this is why the boundary may vary between requests.
Because we have the unique boundary, no encoding of the data is necessary: binary data is sent as is.
TODO: what is the optimal boundary size (log(N)
I bet), and name / running time of the algorithm that finds it? Asked at: https://cs.stackexchange.com/questions/39687/find-the-shortest-sequence-that-is-not-a-sub-sequence-of-a-set-of-sequences
Content-Type
is automatically determined by the browser.
How it is determined exactly was asked at: How is mime type of an uploaded file determined by browser?
Now change the enctype
to application/x-www-form-urlencoded
, reload the browser, and resubmit.
Firefox sent:
POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: application/x-www-form-urlencoded
Content-Length: 51
text1=text+default&text2=a%CF%89b&file1=a.txt&file2=a.html&file3=binary
Clearly the file data was not sent, only the basenames. So this cannot be used for files.
As for the text field, we see that usual printable characters like a
and b
were sent in one byte, while non-printable ones like 0xCF
and 0x89
took up 3 bytes each: %CF%89
!
File uploads often contain lots of non-printable characters (e.g. images), while text forms almost never do.
From the examples we have seen that:
multipart/form-data
: adds a few bytes of boundary overhead to the message, and must spend some time calculating it, but sends each byte in one byte.
application/x-www-form-urlencoded
: has a single byte boundary per field (&
), but adds a linear overhead factor of 3x for every non-printable character.
Therefore, even if we could send files with application/x-www-form-urlencoded
, we wouldn't want to, because it is so inefficient.
But for printable characters found in text fields, it does not matter and generates less overhead, so we just use it.
You probably don't even need string substitution for that. If your original string is JSON, try:
js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz
Be careful with eval
, of course.
This is one of the popular question in any SQL interview. I am going to write down different queries to find out the nth highest value of a column.
I have created a table named “Emloyee” by running the below script.
CREATE TABLE Employee([Eid] [float] NULL,[Ename] [nvarchar](255) NULL,[Basic_Sal] [float] NULL)
Now I am going to insert 8 rows into this table by running below insert statement.
insert into Employee values(1,'Neeraj',45000)
insert into Employee values(2,'Ankit',5000)
insert into Employee values(3,'Akshay',6000)
insert into Employee values(4,'Ramesh',7600)
insert into Employee values(5,'Vikas',4000)
insert into Employee values(7,'Neha',8500)
insert into Employee values(8,'Shivika',4500)
insert into Employee values(9,'Tarun',9500)
Now we will find out 3rd highest Basic_sal from the above table using different queries. I have run the below query in management studio and below is the result.
select * from Employee order by Basic_Sal desc
We can see in the above image that 3rd highest Basic Salary would be 8500. I am writing 3 different ways of doing the same. By running all three mentioned below queries we will get same result i.e. 8500.
First Way: - Using row number function
select Ename,Basic_sal
from(
select Ename,Basic_Sal,ROW_NUMBER() over (order by Basic_Sal desc) as rowid from Employee
)A
where rowid=2
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Even if you do not have the pid, you can trigger 'wait;' after triggering all background processes. For. eg. in commandfile.sh-
bteq < input_file1.sql > output_file1.sql &
bteq < input_file2.sql > output_file2.sql &
bteq < input_file3.sql > output_file3.sql &
wait
Then when this is triggered, as -
subprocess.call(['sh', 'commandfile.sh'])
print('all background processes done.')
This will be printed only after all the background processes are done.
As an additional info to Joey's answer, which isn't described in the help of set /?
nor for /?
.
%~0
expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as
%~0 - mYbAtCh
%~n0 - mybatch
%~nx0 - mybatch.bat
But there is one exception, expanding in a subroutine could fail
echo main- %~0
call :myFunction
exit /b
:myFunction
echo func - %~0
echo func - %~n0
exit /b
This results to
main - myBatch
Func - :myFunction
func - mybatch
In a function %~0
expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!
Use a set to intersect on the dict.viewkeys()
dictionary view:
l = {1, 5}
{key: d[key] for key in d.viewkeys() & l}
This is Python 2 syntax, in Python 3 use d.keys()
.
This still uses a loop, but at least the dictionary comprehension is a lot more readable. Using set intersections is very efficient, even if d
or l
is large.
Demo:
>>> d = {1:2, 3:4, 5:6, 7:8}
>>> l = {1, 5}
>>> {key: d[key] for key in d.viewkeys() & l}
{1: 2, 5: 6}
0..param_count
means "up to and including param_count".
0...param_count
means "up to, but not including param_count".
Range#map
does not return an Enumerable
, it actually maps it to an array. It's the same as Range#to_a
.
If your markup is bound to a controller, directive or anything else with a $scope:
console.log($scope.movie);
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
this should solve your problem
This is for fecha(TEXT) format date YYYY-MM-dd HH:mm:ss for instance I want all the records of Ene-05-2014 (2014-01-05):
SELECT
fecha
FROM
Mytable
WHERE
DATE(substr(fecha ,1,4) ||substr(fecha ,6,2)||substr(fecha ,9,2))
BETWEEN
DATE(20140105)
AND
DATE(20140105);
For Ubuntu, Ctrl + Alt + Left and Ctrl + Alt + Right work fine.
By default these keys are assigned for Ubuntu's workspace navigation.
You need to disable that by going to :
System Settings > Keyboard > Shortcuts Tab > Navigation
and disable Switch to workspace left
and Switch to workspace right
by pressing Backspace.
Or you can choose to change shortcuts in Intellij itself:
File > Settings > Keymap > Main menu > Navigate > Back/Forward
In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.
So in my humble opinion this is a more complete example based on Greg's one:
<?php
class Hello
{
/**
* Construct won't be called inside this class and is uncallable from
* the outside. This prevents instantiating this class.
* This is by purpose, because we want a static class.
*/
private function __construct() {}
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
Try using
<html style="height: 100%;">
<body style="height: 100%;">
<table style="height: 100%;">
...
in order to force all parents of the table
element to expand over the available vertical space (which will eliminate the need to use absolute
positioning).
Works in Firefox 28, IE 11 and Chromium 34 (and hence probably Google Chrome as well)
Source: http://www.dailycoding.com/posts/howtoset100tableheightinhtml.aspx
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Maybe you should better use a case
for such lists:
case "$cms" in
wordpress|meganto|typo3)
do_your_else_case
;;
*)
do_your_then_case
;;
esac
I think for long such lists this is better readable.
If you still prefer the if
you can do it with single brackets in two ways:
if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then
or
if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then
this will set your session to keep everything till the browser is closed
session.setMaxinactiveinterval(-1);
and this should set it for 1 day
session.setMaxInactiveInterval(60*60*24);
sn
ildasm
and ilasm
sn –k Cool.Library.snk
to create a new key pairildasm Cool.Library.dll /out:Cool.Library.il
to disassemble the librarymove Cool.Library.dll Cool.Library.unsigned.dll
to keep the original library as a back-upilasm Cool.Library.il /dll /resource=Cool.Library.res /key=Cool.Library.snk
to reassemble the library with a strong namepowershell -command "& {[System.Reflection.AssemblyName]::GetAssemblyName($args).FullName} Cool.Library.dll"
to get the assembly fully qualified name. You will need this bit if you have to reference the DLL in external configuration files like web.config or app.config.Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
This is what worked for me on ubuntu
curl -L https://www.npmjs.com/install.sh | sh
The below code worked for me in jQuery2.1.3
$("#topbar").animate('{height:"toggle"}');
Need not calculate your div height,padding,margin and borders. It will take care.
Focus is for selecting UI components when you are using something besides touch (ie, a d-pad, a keyboard, etc.). Any view can receive focus, though some are not focusable by default. (You can make a view focusable with setFocusable(true)
and force it to be focused with requestFocus()
.)
However, it is important to note that when you are in touch mode, focus is disabled. So if you are using your fingers, changing the focus programmatically doesn't do anything. The exception to this is for views that receive input from an input editor. An EditText
is such an example. For this special situation setFocusableInTouchMode(true)
is used to let the soft keyboard know where to send input. An EditText
has this setting by default. The soft keyboard will automatically pop up.
If you don't want the soft keyboard popping up automatically then you can temporarily suppress it as @abeljus noted:
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
When a user clicks on the EditText
, it should still show the keyboard, though.
At the end of your lines, simply add the following special character: 
That special character defines the carriage-return character.
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
Also remember that you can pass a second argument to the .forEach()
function specifying the object to use as the this
keyword.
// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
// element is the name of the key.
// key is just a numerical value for the array
// _array is the array of all the keys
// this keyword = secondArg
this.foo;
this.bar();
}, secondArg);
In order to make it work on selection in a list view use the following code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#fff"/>
<item android:state_activated="true" android:color="#fff"/>
<item android:color="#000" />
</selector>
Apparently the key is state_activated="true"
state.
Try with Shadow( Like border ) + Border
border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;
To disable the beep in bash you need to uncomment (or add if not already there) the line set bell-style none
in your /etc/inputrc
file.
Note: Since it is a protected file you need to be a privileged user to edit it (i.e. launch your text editor with something like sudo <editor> /etc/inputrc
).
To disable the beep also in vim you need to add set visualbell
in your ~/.vimrc
file.
To disable the beep also in less (i.e. also in man pages and when using "git diff") you need to add export LESS="$LESS -R -Q"
in your ~/.profile
file.
replace(convert(varchar, getdate(), 111), '/','-')
Will also do trick without "chopping anything off".
It's better to use SUSER_SNAME() since when there is no corresponding login on the server the join to syslogins will not match
SELECT s.name ,
SUSER_SNAME(s.owner_sid) AS owner
FROM msdb..sysjobs s
ORDER BY name
long timestamp = Long.parseLong(date)
Date expiry = new Date(timestamp * 1000)
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.