I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess:
read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)
subprocess.check_call(['your-command'], stdin=read)
SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked . I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies . Full code is given below with exact imports.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFormulaValue {
private static final CellType NUMERIC = null;
public static void main(String[] args) {
try {
readFormula();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
System.out.println("Cell type month is "+cellValue.getCellTypeEnum());
System.out.println("getNumberValue month is "+cellValue.getNumberValue());
// System.out.println("getStringValue "+cellValue.getStringValue());
cellReference = new CellReference("H2"); // pass the cell which contains the formula
row = sheet.getRow(cellReference.getRow());
cell = row.getCell(cellReference.getCol());
cellValue = evaluator.evaluate(cell);
System.out.println("getNumberValue DAY is "+cellValue.getNumberValue());
}
}
Use the styles
left: 0px;
or/and
right: 0px;
or/and
top: 0px;
or/and
bottom: 0px;
I think for most cases that will do the job
Another Anaconda solution. I was getting CERTIFICATE_VERIFY_FAILED in my Python 2.7 environment on macOS. It turns out the conda paths were bad:
base (3.7) environment:
>>> import ssl
>>> ssl.get_default_verify_paths()
DefaultVerifyPaths(cafile='/usr/local/anaconda3/ssl/cert.pem', capath=None, openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/local/anaconda3/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/local/anaconda3/ssl/certs')
2.7 environment (paths did not exist!):
DefaultVerifyPaths(cafile='', capath=None, openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/local/anaconda3/envs/py27/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/local/anaconda3/envs/py27/ssl/certs')
The fix:
cd /usr/local/anaconda3/envs/py27/
mkdir ssl
cd ssl
ln -s ../../../ssl/cert.pem
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
If you want to just uncommit the last commit use this:
git reset HEAD~
work like charm for me.
Remove Object
from NSArray
with this Method:
-(NSArray *) removeObjectFromArray:(NSArray *) array withIndex:(NSInteger) index {
NSMutableArray *modifyableArray = [[NSMutableArray alloc] initWithArray:array];
[modifyableArray removeObjectAtIndex:index];
return [[NSArray alloc] initWithArray:modifyableArray];
}
If you are using Update Panel and link button to download excel is inside the panel than add postback trigger
<asp:PostBackTrigger ControlID="lnkTemplate" />
and in Code behind inside click event
string ServerPath = System.Configuration.ConfigurationManager.AppSettings["FilePath"] + "Template.xlsx";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(ServerPath));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.TransmitFile(file.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
This exact example is present on mozilla developers page:
As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);
, and store it in data-descr="ADD"
attribute of your HTML tag (which is nice because you can e.g translate it)
CSS content
can only be usef with :after
and :before
pseudo-elements, so you can try to proceed with something like this:
.item a p.new-label span:after{
position: relative;
content: 'NEW'
}
.item:hover a p.new-label span:after {
content: 'ADD';
}
The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.
IMO, in your case you can try this:
- Map the shared folder to a drive or folder on your machine. (here's how)
- Access the mapped drive/folder as you normally would local files.
Nothing needs to be installed. No services need to be running except those that enable folder sharing.
If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.
This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.
Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.
If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:
PsExec \\yourServerName -u yourUserName cmd.exe
Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.
I am not sure but I think you need either the Server (lanmanserver
) or the Terminal Services (TermService
) service to be running (which should have already be running).
Another solution for class based vanilla JS using a distance threshold
private initDetectDrag(element) {
let clickOrigin = { x: 0, y: 0 };
const dragDistanceThreshhold = 20;
element.addEventListener('mousedown', (event) => {
this.isDragged = false
clickOrigin = { x: event.clientX, y: event.clientY };
});
element.addEventListener('mousemove', (event) => {
if (Math.sqrt(Math.pow(clickOrigin.y - event.clientY, 2) + Math.pow(clickOrigin.x - event.clientX, 2)) > dragDistanceThreshhold) {
this.isDragged = true
}
});
}
Add inside the class (SOMESLIDER_ELEMENT can also be document to be global):
private isDragged: boolean;
constructor() {
this.initDetectDrag(SOMESLIDER_ELEMENT);
this.doSomeSlideStuff(SOMESLIDER_ELEMENT);
element.addEventListener('click', (event) => {
if (!this.sliderIsDragged) {
console.log('was clicked');
} else {
console.log('was dragged, ignore click or handle this');
}
}, false);
}
For some reason, you can not delete the .idea folder
The best way is
Since this is a Python 3 project, you only need to delete __pycache__
directories -- all .pyc
/.pyo
files are inside them.
find . -type d -name __pycache__ -exec rm -r {} \+
or its simpler form,
find . -type d -name __pycache__ -delete
which didn't work for me for some reason (files were deleted but directories weren't), so I'm including both for the sake of completeness.
Alternatively, if you're doing this in a directory that's under revision control, you can tell the RCS to ignore __pycache__
folders recursively. Then, at the required moment, just clean up all the ignored files. This will likely be more convenient because there'll probably be more to clean up than just __pycache__
.
CSS
select.inpSelect {
//Remove original arrows
-webkit-appearance: none;
//Use png at assets/selectArrow.png for the arrow on the right
//Set the background color to a BadAss Green color
background: url(assets/selectArrow.png) no-repeat right #BADA55;
}
This is a syntax error in your Makefile. It's quite hard to be more specific than that, without seeing the file itself, or relevant portion(s) thereof.
Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.
The matrix representation of the general 2D transformation looks like this:
x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)
where (x,y) are the components of the original vector and (x', y') are the transformed components.
If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:
x' = -y
y' = +x
Same result as given earlier, but with a little more explanation as to where it comes from.
Go to the terminal and write:
rails new <project_name> -d mysql
Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.
You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.
Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.
I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.
Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.
I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.
In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.
Good luck!
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
Not a technical answer but you might want to check the search box for the logcat. If there is any character inputted, your logcat will be empty as it will be searching for that certain character or word, and then if its not present, your logcat log will be totally empty.
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
With "Asset Type" set to "Image", try setting the same image for the foreground and background layers, keeping the same "Resize" percentage.
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
There is a much better way to handle this issue. Rather than removing Hyper-V altogether, you just make alternate boot to temporarily disable it when you need to use VMWare. As shown here...
C:\>bcdedit /copy {current} /d "No Hyper-V"
The entry was successfully copied to {ff-23-113-824e-5c5144ea}.
C:\>bcdedit /set {ff-23-113-824e-5c5144ea} hypervisorlaunchtype off
The operation completed successfully.
note: The ID generated from the first command is what you use in the second one. Don't just run it verbatim.
When you restart, you'll then just see a menu with two options...
So using VMWare is then just a matter of rebooting and choosing the No Hyper-V option.
If you want to remove a boot entry again. You can use the /delete option for bcdedit.
First, get a list of the current boot entries...
C:\>bcdedit /v
This lists all of the entries with their ID's. Copy the relevant ID, and then remove it like so...
C:\>bcdedit /delete {ff-23-113-824e-5c5144ea}
As mentioned in the comments, you need to do this from an elevated command prompt, not powershell. In powershell the command will error.
update: It is possible to run these commands in powershell, if the curly braces are escaped with backtick (`). Like so...
C:\WINDOWS\system32> bcdedit /copy `{current`} /d "No Hyper-V"
I Got the same error.
I just added the @Transactional annotation of javax.transaction.Transactional on the method.
There is no simple and elegant solution to the Redirect
problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution
Dirty: Response.Redirect(url)
sends a redirect to the browser, and then throws a ThreadAbortedException
to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions
will show up in exception logging.
Tedious: The recommended way is to call Response.Redirect(url, false)
and then Context.ApplicationInstance.CompleteRequest()
However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.
(The documentation to CompleteRequest
states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)
The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction
in the controller, without generating a view.
try next:
label[for="userName"] {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
label[for="userName"]::after {_x000D_
content: '[after]';_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
display: inline-block;_x000D_
position: absolute;_x000D_
right: -30px;_x000D_
}
_x000D_
<label for="userName">_x000D_
Name: _x000D_
<input type="text" name="userName" id="userName">_x000D_
</label>
_x000D_
There may be a problem with Maven path configuration, if you used unix-like Operator System.
step 1: create new file in path ~/.bash_profile
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
CLASSPAHT=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
PATH=$JAVA_HOME/bin:$PATH:
export JAVA_HOME
export CLASSPATH
export PATH
step 2: shell run source ~/.bash_profile
OR modify zsh config file(add new line: source ~/.bash_profile
)
Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.
Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?
Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:
this is line 1
this is line 2
the result would be 'this is line 1this is line 2'
... is that what you really want?
A greater solution would include:
onlyascii
recognition that a filter function merely needs to return a truthy value if the argument is to be retained:
def filter_func(char):
return char == '\n' or 32 <= ord(char) <= 126
# and later:
filtered_data = filter(filter_func, data).lower()
A very simple way to read an external script into an sqlite database in python is using executescript()
:
import sqlite3
conn = sqlite3.connect('csc455_HW3.db')
with open('ZooDatabase.sql', 'r') as sql_file:
conn.executescript(sql_file.read())
conn.close()
php.js ( http://www.phpjs.org/ ) has a isset()
function: http://phpjs.org/functions/isset:454
Building on Lauritz` answer, here's a version with the following changes
__call__
instead of __getitem__
from bisect import bisect_right
class Interpolate:
def __init__(self, x_list, y_list):
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")
self.x_list = x_list
self.y_list = y_list
intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
self.slopes = [(y2 - y1) / (x2 - x1) for x1, x2, y1, y2 in intervals]
def __call__(self, x):
if not (self.x_list[0] <= x <= self.x_list[-1]):
raise ValueError("x out of bounds!")
if x == self.x_list[-1]:
return self.y_list[-1]
i = bisect_right(self.x_list, x) - 1
return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
Example usage:
>>> interp = Interpolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4])
>>> interp(4)
5.425
$(document).ready(function() {
$('#div_one').bind('click', function() {
$('#div_two').addClass('large');
});
});
If I understood your question.
Or you can modify css directly:
var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');
Comparing to Apple's UINavigationController
and UIViewController
, Google does not do well in Android software architecture. And Android's document about Fragment
does not help much.
When you enter FragmentB from FragmentA, the existing FragmentA instance is not destroyed. When you press Back in FragmentB and return to FragmentA, we don't create a new FragmentA instance. The existing FragmentA instance's onCreateView()
will be called.
The key thing is we should not inflate view again in FragmentA's onCreateView()
, because we are using the existing FragmentA's instance. We need to save and reuse the rootView.
The following code works well. It does not only keep fragment state, but also reduces the RAM and CPU load (because we only inflate layout if necessary). I can't believe Google's sample code and document never mention it but always inflate layout.
Version 1(Don't use version 1. Use version 2)
public class FragmentA extends Fragment {
View _rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (_rootView == null) {
// Inflate the layout for this fragment
_rootView = inflater.inflate(R.layout.fragment_a, container, false);
// Find and setup subviews
_listView = (ListView)_rootView.findViewById(R.id.listView);
...
} else {
// Do not inflate the layout again.
// The returned View of onCreateView will be added into the fragment.
// However it is not allowed to be added twice even if the parent is same.
// So we must remove _rootView from the existing parent view group
// (it will be added back).
((ViewGroup)_rootView.getParent()).removeView(_rootView);
}
return _rootView;
}
}
------Update on May 3 2005:-------
As the comments mentioned, sometimes _rootView.getParent()
is null in onCreateView
, which causes the crash. Version 2 removes _rootView in onDestroyView(), as dell116 suggested. Tested on Android 4.0.3, 4.4.4, 5.1.0.
Version 2
public class FragmentA extends Fragment {
View _rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (_rootView == null) {
// Inflate the layout for this fragment
_rootView = inflater.inflate(R.layout.fragment_a, container, false);
// Find and setup subviews
_listView = (ListView)_rootView.findViewById(R.id.listView);
...
} else {
// Do not inflate the layout again.
// The returned View of onCreateView will be added into the fragment.
// However it is not allowed to be added twice even if the parent is same.
// So we must remove _rootView from the existing parent view group
// in onDestroyView() (it will be added back).
}
return _rootView;
}
@Override
public void onDestroyView() {
if (_rootView.getParent() != null) {
((ViewGroup)_rootView.getParent()).removeView(_rootView);
}
super.onDestroyView();
}
}
WARNING!!!
This is a HACK! Though I am using it in my app, you need to test and read comments carefully.
Remove a file extension through .htaccess:
Original URL: http://ravinderrathore.herobo.com/contact.php
.htaccess rule to remove .php, .html, etc. file extensions from URLs:
RewriteRule ^(.*)$ $1.php
After Rewriting: http://ravinderrathore.herobo.com/contact
RewriteEngine on
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^index(.*)?$ index.php$1 [L,QSA]
RewriteRule ^login_success(/)?$ login_success.php [L,QSA]
RewriteRule ^contact(/)?$ contact.php [L,QSA]
You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);
I'm writing this answer w.r.t. to python 3, as I've initially got the same problem.
I was supposed to get data from arduino using PySerial
, and write them in a .csv file. Each reading in my case ended with '\r\n'
, so newline was always separating each line.
In my case, newline=''
option didn't work. Because it showed some error like :
with open('op.csv', 'a',newline=' ') as csv_file:
ValueError: illegal newline value: ''
So it seemed that they don't accept omission of newline here.
Seeing one of the answers here only, I mentioned line terminator in the writer object, like,
writer = csv.writer(csv_file, delimiter=' ',lineterminator='\r')
and that worked for me for skipping the extra newlines.
Have you converted your data from string to JavaScript object?
You can do it with data = eval('(' + string_data + ')');
or, which is safer, data = JSON.parse(string_data);
but later will only works in FF 3.5 or if you include json2.js
jQuery since 1.4.1 also have function for that, $.parseJSON()
.
But actually, $.getJSON()
should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.
it may be very old post, but I would like to share my experience. I had the same issue when I used Pycharm and I installed the package from Project Interpreter page in the Project Settings/Preferences... That fixed the issue, please check below link: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html?_ga=2.41088674.1813230270.1594526819-1842497340.1594080707
To make it with jquery, make this way:
var test = $("input[name=testing]:hidden");
test.val('work!');
Or
var test = $("input[name=testing]:hidden").val('work!');
See working in this fiddle.
You may take a look at the following blog post which illustrates a technique that could be used to parse multipart/form-data
on the server using the Multipart Parser:
public void Upload(Stream stream)
{
MultipartParser parser = new MultipartParser(stream);
if (parser.Success)
{
// Save the file
SaveFile(parser.Filename, parser.ContentType, parser.FileContents);
}
}
Another possibility is to enable aspnet compatibility and use HttpContext.Current.Request
but that's not a very WCFish way.
One hint about the "background-size: cover" solution, you have to put it after "background" definition, otherwise it won't work, for example this won't work:
html, body {
height: 100%;
background-size: cover;
background:url("http://i.imgur.com/aZO5Kolb.jpg") no-repeat center center fixed;
}
For each works with JQuery as in
$(<selector>).each(function() {
//this points to item
alert('<msg>');
});
JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/
Check it out, works really well.
HTH.
var test_obj = from d in repository.DbPricing
join d1 in repository.DbOfficeProducts on d.OfficeProductId equals d1.Id
join d2 in repository.DbOfficeProductDetails on d1.ProductDetailsId equals d2.Id
select new
{
PricingId = d.Id,
LetterColor = d2.LetterColor,
LetterPaperWeight = d2.LetterPaperWeight
};
http://www.cybertechquestions.com/select-across-multiple-tables-in-entity-framework-resulting-in-a-generic-iqueryable_222801.html
getApplicationContext() - Returns the context for all activities running in application.
getBaseContext() - If you want to access Context from another context within application you can access.
getContext() - Returns the context view only current running activity.
Your last for
statement is missing a body.
Python expects an indented block to follow the line with the for, or to have content after the colon.
The first style is more common, so it says it expects some indented code to follow it. You have an elif
at the same indent level.
On Windows and Linux, it's AltShiftA, as RichieHindle pointed out. On OSX it's OptionCommandA (??A). It's also worth noting that the two modes can have different font preferences, so if you've changed the default text font, it can be jarring to toggle block selection modes and see the font change.
Finally, the "search commands" (Ctrl3 or Command3) pop-up will find it for you if you type block. This is useful if you use the feature just frequently enough to forget the hotkey.
Everyone already answered but just for the latest updates. If you want to know where all the configuration files reside then run this command in the shell
SELECT name, setting FROM pg_settings WHERE category = 'File Locations';
The Path
objects in path library offer both a context manager and a chdir
method for this purpose:
from path import Path
with Path("somewhere"):
...
Path("somewhere").chdir()
This is about recent additions to AngularJS, to serve as future answer (also for another question).
Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions
, like
ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"
Example:
<input type="text" name="username"
ng-model="user.name"
ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />
Try to use java.util.Arrays
. This module has a variety of useful methods that could be used related to Arrays.
Arrays.toString(your_array_here[]);
You can create new Event handler in the ViewModel like this.
public event EventHandler RequestClose;
protected void OnRequestClose()
{
if (RequestClose != null)
RequestClose(this, EventArgs.Empty);
}
Then Define RelayCommand for ExitCommand.
private RelayCommand _CloseCommand;
public ICommand CloseCommand
{
get
{
if(this._CloseCommand==null)
this._CloseCommand=new RelayCommand(CloseClick);
return this._CloseCommand;
}
}
private void CloseClick(object obj)
{
OnRequestClose();
}
Then In XAML file set
<Button Command="{Binding CloseCommand}" />
Set the DataContext in the xaml.cs File and Subscribe to the event we created.
public partial class MainWindow : Window
{
private ViewModel mainViewModel = null;
public MainWindow()
{
InitializeComponent();
mainViewModel = new ViewModel();
this.DataContext = mainViewModel;
mainViewModel.RequestClose += delegate(object sender, EventArgs args) { this.Close(); };
}
}
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
df = pd.DataFrame({
'client_scripting_ms' : client_scripting_ms,
'apimlayer' : apimlayer, 'server' : server
}, index = index)
ax = df.plot(kind = 'barh',
stacked = True,
title = "Chart",
width = 0.20,
align='center',
figsize=(7,5))
plt.legend(loc='upper right', frameon=True)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('right')
os.path.relpath
as a shell functionThe goal of this relpath
exercise is to mimic Python 2.7's os.path.relpath
function (available from Python version 2.6 but only working properly in 2.7), as proposed by xni. As a consequence, some of the results may differ from functions provided in other answers.
(I have not tested with newlines in paths simply because it breaks the validation based on calling python -c
from ZSH. It would certainly be possible with some effort.)
Regarding “magic” in Bash, I have given up looking for magic in Bash long ago, but I have since found all the magic I need, and then some, in ZSH.
Consequently, I propose two implementations.
The first implementation aims to be fully POSIX-compliant. I have tested it with /bin/dash
on Debian 6.0.6 “Squeeze”. It also works perfectly with /bin/sh
on OS X 10.8.3, which is actually Bash version 3.2 pretending to be a POSIX shell.
The second implementation is a ZSH shell function that is robust against multiple slashes and other nuisances in paths. If you have ZSH available, this is the recommended version, even if you are calling it in the script form presented below (i.e. with a shebang of #!/usr/bin/env zsh
) from another shell.
Finally, I have written a ZSH script that verifies the output of the relpath
command found in $PATH
given the test cases provided in other answers. I added some spice to those tests by adding some spaces, tabs, and punctuation such as ! ? *
here and there and also threw in yet another test with exotic UTF-8 characters found in vim-powerline.
First, the POSIX-compliant shell function. It works with a variety of paths, but does not clean multiple slashes or resolve symlinks.
#!/bin/sh
relpath () {
[ $# -ge 1 ] && [ $# -le 2 ] || return 1
current="${2:+"$1"}"
target="${2:-"$1"}"
[ "$target" != . ] || target=/
target="/${target##/}"
[ "$current" != . ] || current=/
current="${current:="/"}"
current="/${current##/}"
appendix="${target##/}"
relative=''
while appendix="${target#"$current"/}"
[ "$current" != '/' ] && [ "$appendix" = "$target" ]; do
if [ "$current" = "$appendix" ]; then
relative="${relative:-.}"
echo "${relative#/}"
return 0
fi
current="${current%/*}"
relative="$relative${relative:+/}.."
done
relative="$relative${relative:+${appendix:+/}}${appendix#/}"
echo "$relative"
}
relpath "$@"
Now, the more robust zsh
version. If you would like it to resolve the arguments to real paths à la realpath -f
(available in the Linux coreutils
package), replace the :a
on lines 3 and 4 with :A
.
To use this in zsh, remove the first and last line and put it in a directory that is in your $FPATH
variable.
#!/usr/bin/env zsh
relpath () {
[[ $# -ge 1 ]] && [[ $# -le 2 ]] || return 1
local target=${${2:-$1}:a} # replace `:a' by `:A` to resolve symlinks
local current=${${${2:+$1}:-$PWD}:a} # replace `:a' by `:A` to resolve symlinks
local appendix=${target#/}
local relative=''
while appendix=${target#$current/}
[[ $current != '/' ]] && [[ $appendix = $target ]]; do
if [[ $current = $appendix ]]; then
relative=${relative:-.}
print ${relative#/}
return 0
fi
current=${current%/*}
relative="$relative${relative:+/}.."
done
relative+=${relative:+${appendix:+/}}${appendix#/}
print $relative
}
relpath "$@"
Finally, the test script. It accepts one option, namely -v
to enable verbose output.
#!/usr/bin/env zsh
set -eu
VERBOSE=false
script_name=$(basename $0)
usage () {
print "\n Usage: $script_name SRC_PATH DESTINATION_PATH\n" >&2
exit ${1:=1}
}
vrb () { $VERBOSE && print -P ${(%)@} || return 0; }
relpath_check () {
[[ $# -ge 1 ]] && [[ $# -le 2 ]] || return 1
target=${${2:-$1}}
prefix=${${${2:+$1}:-$PWD}}
result=$(relpath $prefix $target)
# Compare with python's os.path.relpath function
py_result=$(python -c "import os.path; print os.path.relpath('$target', '$prefix')")
col='%F{green}'
if [[ $result != $py_result ]] && col='%F{red}' || $VERBOSE; then
print -P "${col}Source: '$prefix'\nDestination: '$target'%f"
print -P "${col}relpath: ${(qq)result}%f"
print -P "${col}python: ${(qq)py_result}%f\n"
fi
}
run_checks () {
print "Running checks..."
relpath_check '/ a b/å/?*/!' '/ a b/å/?/xäå/?'
relpath_check '/' '/A'
relpath_check '/A' '/'
relpath_check '/ & / !/*/\\/E' '/'
relpath_check '/' '/ & / !/*/\\/E'
relpath_check '/ & / !/*/\\/E' '/ & / !/?/\\/E/F'
relpath_check '/X/Y' '/ & / !/C/\\/E/F'
relpath_check '/ & / !/C' '/A'
relpath_check '/A / !/C' '/A /B'
relpath_check '/Â/ !/C' '/Â/ !/C'
relpath_check '/ & /B / C' '/ & /B / C/D'
relpath_check '/ & / !/C' '/ & / !/C/\\/Ê'
relpath_check '/Å/ !/C' '/Å/ !/D'
relpath_check '/.A /*B/C' '/.A /*B/\\/E'
relpath_check '/ & / !/C' '/ & /D'
relpath_check '/ & / !/C' '/ & /\\/E'
relpath_check '/ & / !/C' '/\\/E/F'
relpath_check /home/part1/part2 /home/part1/part3
relpath_check /home/part1/part2 /home/part4/part5
relpath_check /home/part1/part2 /work/part6/part7
relpath_check /home/part1 /work/part1/part2/part3/part4
relpath_check /home /work/part2/part3
relpath_check / /work/part2/part3/part4
relpath_check /home/part1/part2 /home/part1/part2/part3/part4
relpath_check /home/part1/part2 /home/part1/part2/part3
relpath_check /home/part1/part2 /home/part1/part2
relpath_check /home/part1/part2 /home/part1
relpath_check /home/part1/part2 /home
relpath_check /home/part1/part2 /
relpath_check /home/part1/part2 /work
relpath_check /home/part1/part2 /work/part1
relpath_check /home/part1/part2 /work/part1/part2
relpath_check /home/part1/part2 /work/part1/part2/part3
relpath_check /home/part1/part2 /work/part1/part2/part3/part4
relpath_check home/part1/part2 home/part1/part3
relpath_check home/part1/part2 home/part4/part5
relpath_check home/part1/part2 work/part6/part7
relpath_check home/part1 work/part1/part2/part3/part4
relpath_check home work/part2/part3
relpath_check . work/part2/part3
relpath_check home/part1/part2 home/part1/part2/part3/part4
relpath_check home/part1/part2 home/part1/part2/part3
relpath_check home/part1/part2 home/part1/part2
relpath_check home/part1/part2 home/part1
relpath_check home/part1/part2 home
relpath_check home/part1/part2 .
relpath_check home/part1/part2 work
relpath_check home/part1/part2 work/part1
relpath_check home/part1/part2 work/part1/part2
relpath_check home/part1/part2 work/part1/part2/part3
relpath_check home/part1/part2 work/part1/part2/part3/part4
print "Done with checks."
}
if [[ $# -gt 0 ]] && [[ $1 = "-v" ]]; then
VERBOSE=true
shift
fi
if [[ $# -eq 0 ]]; then
run_checks
else
VERBOSE=true
relpath_check "$@"
fi
Here is the solution. I have fixed it. Here is the code
child: _status(data[index]["status"]),
Widget _status(status) {
if (status == "3") {
return Text('Process');
} else if(status == "1") {
return Text('Order');
} else {
return Text("Waiting");
}
}
vars()['meta_anio_2012'] = 'translate'
I would omit the * { text-align:center }
declaration, as it sets center alignment for all elements.
Usually with a fixed width container margin: 0 auto
should be enough
For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe
in case it is not found in the path:
(Still Reimeus' suggestion should be your first attempt.)
1.
Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome
2.
Newer versions of JRE/JDK, seem to also place a copy of javaw.exe
in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).
3.
Of course there are the "usual" install locations:
[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]
A little while back, I wrote this piece of code to check for javaw.exe
in the aforementioned places. Maybe someone finds it useful:
static protected String findJavaw() {
Path pathToJavaw = null;
Path temp;
/* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
List<String> output = new ArrayList<>();
executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "CurrentVersion"},
output);
Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
for (String line : output) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
keyNode += "\\" + matcher.group(1);
List<String> output2 = new ArrayList<>();
executeCommand(
new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "JavaHome"},
output2);
Pattern pattern2
= Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
for (String line2 : output2) {
Matcher matcher2 = pattern2.matcher(line2);
if (matcher2.find()) {
pathToJavaw = Paths.get(matcher2.group(1), "bin",
"javaw.exe");
break;
}
}
break;
}
}
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Windows\System32' */
pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Program Files\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
return "javaw.exe"; // Let's just hope it is in the path :)
}
// Without Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
variable = a;
}
};
Here compiler follows following steps to create an object of type MyClass
1. Type’s constructor is called first for “a”.
2. The assignment operator of “Type” is called inside body of MyClass() constructor to assign
variable = a;
And then finally destructor of “Type” is called for “a” since it goes out of scope.
Now consider the same code with MyClass() constructor with Initializer List
// With Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a):variable(a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
}
};
With the Initializer List, following steps are followed by compiler:
This worked fine for me (C#):
byte[] iconBytes = null;
using (var dbConnection = new SQLiteConnection(DataSource))
{
dbConnection.Open();
using (var transaction = dbConnection.BeginTransaction())
{
using (var command = new SQLiteCommand(dbConnection))
{
command.CommandText = "SELECT icon FROM my_table";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"]))
{
iconBytes = (byte[]) reader["icon"];
}
}
}
}
transaction.Commit();
}
}
No need for chunking. Just cast to a byte array.
Your local branch likely has modifications to it you want to discard. To do this, you'll need to use git reset
to reset the branch head to the last spot that you diverged from the upstream repo's branch. Use git branch -v
to find the sha1 id of the upstream branch, and reset your branch it it using git reset SHA1ID
. Then you should be able to do a git checkout
to discard the changes it left in your directory.
Note: always do this on a backed-up repo. That way you can assure you're self it worked right. Or if it didn't, you have a backup to revert to.
Eclipse's compiler can assure that your java sources conform to a given JDK version even if you don't have that version installed. This feature is useful for ensuring backwards compatibility of your code.
Your code will still be compiled and run by the JDK you've selected.
Use jquery, look how easy it is:
var a = '<h1> this is some html </h1>';
$("#results").html(a);
//html
<div id="results"> </div>
Use xsd:include brings all declarations and definitions of an external schema document into the current schema.
Use xsd:import to bring in an XSD from a different namespace and used to build a new schema by extending existing schema documents..
In my case, there were two different 'AWS_SECRET_ACCESS_KEY' and 'AWS_ACCESS_KEY_ID' values set one through the Windows environment variable and one through the command line.
So, update these two and the default_region using a command line
> aws configure
Press enter and follow the steps to fill the correct
AWS_ACESS_KEY_ID
AWS_SECRET_ACCESS_KEY
and AWS_DEFAULT_REGION
> aws sts get-caller-identity
should return the new set credentials
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
The javascript array has a constructor that accepts the length of the array:
let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]
However, this is just the initial size, there's no restriction on changing that:
arr.push(5);
console.log(arr); // [undefined × 3, 5]
Typescript has tuple types which let you define an array with a specific length and types:
let arr: [number, number, number];
arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {_x000D_
$(window).scroll(function fix_element() {_x000D_
$('#target').css(_x000D_
$(window).scrollTop() > 100_x000D_
? { 'position': 'fixed', 'top': '10px' }_x000D_
: { 'position': 'relative', 'top': 'auto' }_x000D_
);_x000D_
return fix_element;_x000D_
}());_x000D_
});
_x000D_
body {_x000D_
height: 2000px;_x000D_
padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
padding: 5px;_x000D_
background: #efefef;_x000D_
}_x000D_
#target {_x000D_
color: #c00;_x000D_
font: 15px arial;_x000D_
padding: 10px;_x000D_
margin: 10px;_x000D_
border: 1px solid #c00;_x000D_
width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
@Edinator have a look on this..
myLabel.font = [UIFont boldSystemFontOfSize:16.0f]
myLabel.font = [UIFont italicSystemFontOfSize:16.0f];
use any one of the above at a time you want
You are probably missing the viewport meta tag in the html head:
<meta name="viewport" content="width=device-width, initial-scale=1">
Without it the device assumes and sets the viewport to full size.
More info here.
The following snippets test for the "not contains" condition, as exemplified in the sample pseudocode in the question. For a direct solution with explicit looping, do this:
boolean contains = false;
for (char c : charArray) {
if (c == 'q') {
contains = true;
break;
}
}
if (!contains) {
// do something
}
Another alternative, using the fact that String
provides a contains()
method:
if (!(new String(charArray).contains("q"))) {
// do something
}
Yet another option, this time using indexOf()
:
if (new String(charArray).indexOf('q') == -1) {
// do something
}
I've used Blat ( http://www.blat.net/ ) for many years. It's a simple command line utility that can send email from command line. It's free and opensource.
You can use command like "Blat myfile.txt -to [email protected] -server smtp.domain.com -port 6000"
Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software
The following VBScript code is taken from that page
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "[email protected]"
objEmail.To = "[email protected]"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send
Save the file as something.vbs
Set Msg = CreateObject("CDO.Message")
With Msg
.To = "[email protected]"
.From = "[email protected]"
.Subject = "Hello"
.TextBody = "Just wanted to say hi."
.Send
End With
Save the file as something2.vbs
I think these VBS scripts use the windows default mail server, if present. I've not tested these scripts...
I found another solution here, since I ran into both post...
This is from the Myles answer:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
This worked for me.
I experienced these errors when I was developing an npm package that had peerDependencies
. I had to ensure that any peerDependencies
were also listed as devDependencies
. The project would not automatically use the globally installed packages.
Much easier way in PowerShell:
Get-ADPrincipalGroupMembership <username>
Requirement: the account you yourself are running under must be a member of the same domain as the target user, unless you specify -Credential
and -Server
(untested).
In addition, you must have the Active Directory Powershell module installed, which as @dave-lucre says in a comment to another answer, is not always an option.
For group names only, try one of these:
(Get-ADPrincipalGroupMembership <username>).Name
Get-ADPrincipalGroupMembership <username> |Select Name
use Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});
@K Scott Piel wrote a great answer here, but I want to add one important point.
Note that the stdout
stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf
statement with a \n
Ex:
printf("hello world\n");
or
printf("hello world");
printf("\n");
or similar, OR you must call fflush(stdout);
after your printf
call.
Ex:
printf("hello world");
fflush(stdout);
Read more here: Why does printf not flush after the call unless a newline is in the format string?
ESC and CTRL-BREAK did not work for me just now. But CTRL-ESC worked!? No idea why, but I thought I would throw it out there in case it helps someone else. (I had forgotten i = i + 1 in my loop...)
You can also use sqlcmd
mode for this (enable this on the "Query" menu in Management Studio).
:setvar dbname "TEST"
CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE
GO
EDIT:
Check this MSDN article to set parameters via the SQLCMD tool.
Since mysql_connect
has been deprecated, connect and query instead with mysqli:
$mysqli = new mysqli("hostname","username","password","database_name");
$sqlSelect="SELECT your_fieldname FROM your_table";
$result = $mysqli -> query ($sqlSelect);
And then, if you have more than one option list with the same values on the same page, put the values in an array:
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
And then you can loop the array multiple times on the same page:
foreach ($rows as $row) {
print "<option value='" . $row['your_fieldname'] . "'>" . $row['your_fieldname'] . "</option>";
}
Recently migrated from mongodb to Postgres. This is how I used the scripts.
mongo < scripts.js > inserts.sql
Read the scripts.js
and output redirect to inserts.sql
.
scripts.js
looks like this
use myDb;
var string = "INSERT INTO table(a, b) VALUES";
db.getCollection('collectionName').find({}).forEach(function (object) {
string += "('" + String(object.description) + "','" + object.name + "'),";
});
print(string.substring(0, string.length - 1), ";");
inserts.sql
looks like this
INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');
If you want to print the bytes as chars you can use the String constructor.
byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));
If you use the 'Export Data' wizard there is an option to store the configuration as an 'Integration Services Projects' within the SQL Server database . To edit this package follow the instructions from "mikeTheLiar" but instead of searching for a file make a connection to the database and export package.
From "mikeTheLiar": File->New Project->Integration Services Project - Now in solution explorer there is a SSIS Packages folder, right click it and select "Add Existing Package".
Using the default dialog make a connection to the database and open the export package. The package can now be edited.
As Mark pointed out, you should use .title()
:
"MyAwesomeString".title()
However, if would like to make the first letter uppercase inside a Django template, you could use this:
{{ "MyAwesomeString"|title }}
Or using a variable:
{{ myvar|title }}
if you are otherwise using numpy, you can save a few strokes, but i dont think it gets much faster/compact than senderle's answer.
import numpy as np
j = np.array(j)
sum(j > i)
I think you need to set symbreaks = FALSE
That should allow for asymmetrical color scales.
A jar
file is a zip file with some additional files containing metadata. (Despite the .jar extension, it is in zip format, and any utilities that deal with .zip files are also able to deal with .jar files.)
http://docs.oracle.com/javase/8/docs/technotes/guides/jar/index.html
Jar files can contain any kind of files, but they usually contain class files and supporting configuration files (properties), graphics and other data files needed by the application.
Class files contain compiled Java code, which is executable by the Java Virtual Machine.
For this requirement, I implement and publish a generic component. See
https://www.npmjs.com/package/w-ng5
For use this components, before, install this package with npm:
npm install w-ng5 --save
After, import module in app.module
...
import { PipesModule } from 'w-ng5';
In the next step, add in declare section of app.module:
imports: [
PipesModule,
...
]
Sample use
Filtering simple string
<input type="text" [(ngModel)]="filtroString">
<ul>
<li *ngFor="let s of getStrings() | filter:filtroString">
{{s}}
</li>
</ul>
Filtering complex string - field 'Value' in level 2
<input type="text" [(ngModel)]="search">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering complex string - middle field - 'Value' in level 1
<input type="text" [(ngModel)]="search3">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.valor1', value: search3}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering complex array simple - field 'Nome' level 0
<input type="text" [(ngModel)]="search2">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'nome', value: search2}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering in tree fields - field 'Valor' in level 2 or 'Valor' in level 1 or 'Nome' in level 0
<input type="text" [(ngModel)]="search5">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search5}, {field:'n1.valor1', value: search5}, {field:'nome', value: search5}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering nonexistent field - 'Valor' in nonexistent level 3
<input type="text" [(ngModel)]="search4">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.n3.valor3', value: search4}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
This component work with infinite attribute level...
Most popular C# Data Structures and Collections
C#.NET has a lot of different data structures, for example, one of the most common ones is an Array. However C# comes with many more basic data structures. Choosing the correct data structure to use is part of writing a well structured and efficient program.
In this article I will go over the built-in C# data structures, including the new ones introduces in C#.NET 3.5. Note that many of these data structures apply for other programming languages.
Array
The perhaps simplest and most common data structure is the array. A C# array is basically a list of objects. Its defining traits are that all the objects are the same type (in most cases) and there is a specific number of them. The nature of an array allows for very fast access to elements based on their position within the list (otherwise known as the index). A C# array is defined like this:
[object type][] myArray = new [object type][number of elements]
Some examples:
int[] myIntArray = new int[5];
int[] myIntArray2 = { 0, 1, 2, 3, 4 };
As you can see from the example above, an array can be intialized with no elements or from a set of existing values. Inserting values into an array is simple as long as they fit. The operation becomes costly when there are more elements than the size of the array, at which point the array needs to be expanded. This takes longer because all the existing elements must be copied over to the new, bigger array.
ArrayList
The C# data structure, ArrayList, is a dynamic array. What that means is an ArrayList can have any amount of objects and of any type. This data structure was designed to simplify the processes of adding new elements into an array. Under the hood, an ArrayList is an array whose size is doubled every time it runs out of space. Doubling the size of the internal array is a very effective strategy that reduces the amount of element-copying in the long run. We won't get into the proof of that here. The data structure is very simple to use:
ArrayList myArrayList = new ArrayList();
myArrayList.Add(56);
myArrayList.Add("String");
myArrayList.Add(new Form());
The downside to the ArrayList data structure is one must cast the retrived values back into their original type:
int arrayListValue = (int)myArrayList[0]
Sources and more info you can find here :
One solution (though not very pretty) is to use Apache common List/Set mutation
import org.apache.commons.collections.list.SetUniqueList;
final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());
it is a list without duplicates
if min=10
and max=100
:
(int)(Math.random() * max) + min
gives a result between 10 and 110, while
(int)(Math.random() * (max - min) + min)
gives a result between 10 and 100, so they are very different formulas. What's important here is clarity, so whatever you do, make sure the code makes it clear what is being generated.
(PS. the first makes more sense if you change the variable 'max' to be called 'range')
The method len() returns the number of elements in the list.
Syntax:
len(myArray)
Eg:
myArray = [1, 2, 3]
len(myArray)
Output:
3
awk -F, '{ print $3, $0 }' user.csv | sort -nk2
and for reverse order
awk -F, '{ print $3, $0 }' user.csv | sort -nrk2
My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
Usage:
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
Features:
start()
and stop()
are safe to call multiple times even if the timer has already started/stoppedinterval
anytime, it will be effective after next run. Same for args
, kwargs
and even function
!What other answers missed, is that the path given to the function could actually be a directory. Following function makes sure, that the path is really a file.
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
Another thing to point out: This code could still lead to a race condition, where another thread or process deletes or creates the specified file, while the fileExists function is running.
If you're worried about this, use a lock in your threads, serialize the access to this function or use an inter-process semaphore if multiple applications are involved. If other applications are involved, outside of your control, you're out of luck, I guess.
Use the date_trunc
method to truncate off the day (or whatever else you want, e.g., week, year, day, etc..)
Example of grouping sales from orders by month:
select
SUM(amount) as sales,
date_trunc('month', created_at) as date
from orders
group by date
order by date DESC;
Try below method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 100.0, height: 100.0)
}
It isn't an environment variable, but still gives you control over the temp dir:
-Djava.io.tmpdir
ex.:
java -Djava.io.tmpdir=/mytempdir
The 'find' method can be used to get all child inputs of a container that has already been cached to save looking it up again (whereas the 'children' method will only get the immediate children). e.g.
var panel= $("#panel");
var inputs = panel.find("input");
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir()
returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir()
returns only true if mkDir()
creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists()
if mkDir()
return false.
assertThat()
will checks the result and fails if exists()
returns false. ofc you can use other things to handle the uncreated directory.
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
So here is the solution for this:
I check port 80
used by Skype, after that I changes port to 81
and also along with that somewhere i read this error may be because of SSL Port then I changed SSL port to 444
. However this got resolved easily.
One most important thing to notice here, all the port changes should be done inside config files, for http port change: httpd.conf for SSL httpd-ssl.conf. Otherwise changes will not replicate to Apache, Sometime PC reboot is also required.
Edit: Make Apache use port 80 and make Skype communicate on other Port
For those who are struggling with Skype, want to change its port and to make Apache to use port 80.
No need to Re-Install, Here is simply how to change Skype Port
Goto: Tools > Options > Advanced > Connection
There you need to uncheck
Use port 80 and 443 as alternative for incoming connections.
That's it, here is screen shot of it.
this piece of code can do its job
UPDATE TOP (100) table_name set column_name = value;
If you want to show the last 100 records, you can use this if you need.
With OrnekWith
as
(
Select Top(100) * from table_name Order By ID desc
)
Update table_name Set column_name = value;
Add these methods to your Activity:
private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
myServiceBinder = ((MyService.MyBinder) binder).getService();
Log.d("ServiceConnection","connected");
showServiceData();
}
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
};
public Handler myHandler = new Handler() {
public void handleMessage(Message message) {
Bundle data = message.getData();
}
};
public void doBindService() {
Intent intent = null;
intent = new Intent(this, BTService.class);
// Create a new Messenger for the communication back
// From the Service to the Activity
Messenger messenger = new Messenger(myHandler);
intent.putExtra("MESSENGER", messenger);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.
@Override
protected void onResume() {
Log.d("activity", "onResume");
if (myService == null) {
doBindService();
}
super.onResume();
}
@Override
protected void onPause() {
//FIXME put back
Log.d("activity", "onPause");
if (myService != null) {
unbindService(myConnection);
myService = null;
}
super.onPause();
}
Note, that when binding to a service only the onCreate()
method is called in the service class.
In your Service class you need to define the myBinder method:
private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;
@Override
public IBinder onBind(Intent arg0) {
Bundle extras = arg0.getExtras();
Log.d("service","onBind");
// Get messager from the Activity
if (extras != null) {
Log.d("service","onBind with extra");
outMessenger = (Messenger) extras.get("MESSENGER");
}
return mBinder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
After you defined these methods you can reach the methods of your service at your Activity:
private void showServiceData() {
myServiceBinder.myMethod();
}
and finally you can start your service when some event occurs like _BOOT_COMPLETED_
public class MyReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, myService.class);
context.startService(service);
}
}
}
note that when starting a service the onCreate()
and onStartCommand()
is called in service class
and you can stop your service when another event occurs by stopService()
note that your event listener should be registerd in your Android manifest file:
<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This occurs when you try and write to a file that is currently being executed by the kernel, or execute a file that is currently open for writing.
Source: http://wiki.wlug.org.nz/ETXTBSY
You should use #!/usr/bin/env bash
for portability: different *nixes put bash
in different places, and using /usr/bin/env
is a workaround to run the first bash
found on the PATH
. And sh
is not bash
.
The CSS solutions posted by others are the best way to accomplish this.
If that should give you any problems (read IE6), you can also use a borderless input inside of a div.
<div style="border: 1px solid #DDD;">
<img src="icon.png"/>
<input style="border: none;"/>
</div>
Not as "clean", but should work on older browsers.
here is the sample code to draw image on canvas-
$("#selectedImage").change(function(e) {
var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 500, 500);
}});
In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
const romanize = num => {_x000D_
const romans = {_x000D_
M:1000,_x000D_
CM:900,_x000D_
D:500,_x000D_
CD:400,_x000D_
C:100,_x000D_
XC:90,_x000D_
L:50,_x000D_
XL:40,_x000D_
X:10,_x000D_
IX:9,_x000D_
V:5,_x000D_
IV:4,_x000D_
I:1_x000D_
};_x000D_
_x000D_
let roman = '';_x000D_
_x000D_
for (let key in romans) {_x000D_
const times = Math.trunc(num / romans[key]);_x000D_
roman += key.repeat(times);_x000D_
num -= romans[key] * times;_x000D_
}_x000D_
_x000D_
return roman;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
romanize(38)_x000D_
)
_x000D_
Use the hash (#
) symbol to only display trailing 0's when necessary. See the tests below.
decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;
num1.ToString("0.##"); //13.15%
num2.ToString("0.##"); //49.1%
num3.ToString("0.##"); //30%
As stated in a similar question, try removing instances of the input-group
class and see if that helps.
refering to bootstrap:
Individual form controls automatically receive some global styling. All textual , , and elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.
This is very good: http://simononsoftware.com/virtualenv-tutorial-part-2/
And this is a slightly more practical one: https://web.archive.org/web/20160404222648/https://iamzed.com/2009/05/07/a-primer-on-virtualenv/
I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:
conda config --set auto_activate_base false
The first time you run it, it'll create a ./condarc
in your home directory with that setting to override the default.
This wouldn't de-clutter your .bash_profile
but it's a cleaner solution without manual editing that section that conda manages.
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
Note that this behaves the same on IIS 6 and 7.x, and .NET 2, 3, and 4.x.
Also note that when app_offline.htm is present, IIS will return this http status code:
HTTP/1.1 503 Service Unavailable
This is all by design. This allows your load balancer (or whatever) to see that the server is off line.
The args of print_the_arguments is arguments, so you should use:
struct arg_struct *args = (struct arg_struct *)arguments.
I really recommend you read about Information Theory, bayesian methods and MaxEnt. The place to start is this (freely available online) book by David Mackay:
http://www.inference.phy.cam.ac.uk/mackay/itila/
Those inference methods are really far more general than just text mining and I can't really devise how one would learn how to apply this to NLP without learning some of the general basics contained in this book or other introductory books on Machine Learning and MaxEnt bayesian methods.
The connection between entropy and probability theory to information processing and storing is really, really deep. To give a taste of it, there's a theorem due to Shannon that states that the maximum amount of information you can pass without error through a noisy communication channel is equal to the entropy of the noise process. There's also a theorem that connects how much you can compress a piece of data to occupy the minimum possible memory in your computer to the entropy of the process that generated the data.
I don't think it's really necessary that you go learning about all those theorems on communication theory, but it's not possible to learn this without learning the basics about what is entropy, how it's calculated, what is it's relationship with information and inference, etc...
32bit windows has a 2GB process memory limit. The /3GB boot option others have mentioned will make this 3GB with just 1gb remaining for OS kernel use. Realistically if you want to use more than 2GB without hassle then a 64bit OS is required. This also overcomes the problem whereby although you may have 4GB of physical RAM, the address space requried for the video card can make a sizeable chuck of that memory unusable - usually around 500MB.
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
You can give a try to django-import-export. It has nice admin integration, changes preview, can create, update, delete objects.
If you want to detect all the "states" (first time denied, just been denied, just been denied with "Never Ask Again" or permanently denied) you can do the following:
Create 2 Booleans:
private boolean beforeClickPermissionRat;
private boolean afterClickPermissionRat;
Set the first one before asking for permission:
beforeClickPermissionRat = shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE);
Set the second one inside your onRequestPermissionsResult
method:
afterClickPermissionRat = shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE);
Use the following "truth table" to do whatever you need in onRequestPermissionsResult()
(after checking that you still don't have the permission):
// before after
// FALSE FALSE = Was denied permanently, still denied permanently --> App Settings
// FALSE TRUE = First time deny, not denied permanently yet --> Nothing
// TRUE FALSE = Just been permanently denied --> Changing my caption to "Go to app settings to edit permissions"
// TRUE TRUE = Wasn't denied permanently, still not denied permanently --> Nothing
This solution WORKS , I had the same issue and after hours I came up to this:
(1) Go to your pom.xml
(2) Add this Dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
(3) Run your Project
I had almost precisely the same error, and was able to completely fix it simply by running:
gem install bundler
It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:
sudo gem install bundler
...but generally you can do it without sudo.
try kill -9 {processID}
To find the process ID you can use ps -ef | grep gedit
Set divider to null:
JAVA
listview_id.setDivider(null);
XML
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
/>
At first, you need to add :
after the IP address to indicate the path is following:
scp magento.tar.gz [email protected]:/var/www
I don't think you need to sudo
the scp
. In this case it doesn't affect the remote machine, only the local command.
Then if your user
@xx.x.x.xx doesn't have write access to /var/www
then you need to do it in 2 times:
Copy to remote server in your home folder (:
represents your remote home folder, use :subfolder/
if needed, or :/home/user/
for full path):
scp magento.tar.gz [email protected]:
Then SSH and move the file:
ssh [email protected]
sudo mv magento.tar.gz /var/www
I believe you are now able to use Window.getComputedStyle()
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
window.getComputedStyle(document.querySelector('#mainbar')).width
Write the below code after the PHP, HTML or jQuery section. If in the middle of the PHP or HTML section, then use the <script> tag.
location.href = "http://google.com"
It also important to make sure that the web server sends the file with Content-Disposition = inline. this might not be the case if you are reading the file yourself and send it's content to the browser:
in php it will look like this...
...headers...
header("Content-Disposition: inline; filename=doc.pdf");
...headers...
readfile('localfilepath.pdf')
Dot grammar maybe more swift!
@(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);
109 - mon dd yyyy (In SQL conversion)
The required format is April 1 2009
so
SELECT DATENAME(MONTH, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 109), 9)
Result is:
From the Official Whatsapp FAQ: https://faq.whatsapp.com/en/android/26000030/
WhatsApp's Click to Chat feature allows you to begin a chat with someone without having their phone number saved in your phone's address book. As long as you know this person’s phone number, you can create a link that will allow you to start a chat with them. By clicking the link, a chat with the person automatically opens. Click to Chat works on both your phone and WhatsApp Web.
To create your own link, use https://wa.me/ where the is a full phone number in international format. Omit any zeroes, brackets or dashes when adding the phone number in international format. For a detailed explanation on international numbers, read this article. Please keep in mind that this phone number must have an active account on WhatsApp.
Use: https://wa.me/15551234567
Don't use: https://wa.me/+001-(555)1234567
Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.
<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />
Depending on how much traffic you get, this may be the most practical reason for adding the link.
Info on setting up a cookieless domain:
I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.
Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.
So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
private Func<T, TKey> expr { get; set; }
public GeneralPropertyComparer (Func<T, TKey> expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}
If valuationId
and user
are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
<a href=# onclick="return ReAssign(valuationId,user)">Re-Assign</a>
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo '<a href=# onclick="return ReAssign(\'' + $valuationId + '\',\'' + $user + '\')">Re-Assign</a>';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId + '\',\'' + user + '\')">Re-Assign</a> </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
Here is one way you could do it...
find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"
Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.
So Logic is
if report.type = 'p'
amount = amount
else
amount = -1*amount
SQL
SELECT
id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM report
You may skip abs() if all no's are +ve only
(along CUDA Toolkit 11.0 RC)
To solve the same issue as OP, I just had to find cudart64_101.dll on my disk (in my case C:\Program Files\NVIDIA Corporation\NvStreamSrv) and add it as variable environment (that is add value C:\Program Files\NVIDIA\Corporation\NvStreamSrv)cudart64_101.dll to user's environment variable Path).
Let's assume two dates:
NSDate *date1;
NSDate *date2;
Then the following comparison will tell which is earlier/later/same:
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
} else {
NSLog(@"dates are the same");
}
Please refer to the NSDate class documentation for more details.
If you want to remove the default value constraint, you can do:
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
We could simply write the following method
public static void ClearLine()
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
and then call it when needed like this
Console.WriteLine("Test");
ClearLine();
It works fine for me.
Just use the exec-maven-plugin
.
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>com.example.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
Then you run you program:
mvn exec:java
If your arrays aren't too big or you don't have too many of them, you might be able to get away with forcing the left hand side of ==
to be a string:
myRows = df[str(df['Unnamed: 5']) == 'Peter'].index.tolist()
But this is ~1.5 times slower if df['Unnamed: 5']
is a string, 25-30 times slower if df['Unnamed: 5']
is a small numpy array (length = 10), and 150-160 times slower if it's a numpy array with length 100 (times averaged over 500 trials).
a = linspace(0, 5, 10)
b = linspace(0, 50, 100)
n = 500
string1 = 'Peter'
string2 = 'blargh'
times_a = zeros(n)
times_str_a = zeros(n)
times_s = zeros(n)
times_str_s = zeros(n)
times_b = zeros(n)
times_str_b = zeros(n)
for i in range(n):
t0 = time.time()
tmp1 = a == string1
t1 = time.time()
tmp2 = str(a) == string1
t2 = time.time()
tmp3 = string2 == string1
t3 = time.time()
tmp4 = str(string2) == string1
t4 = time.time()
tmp5 = b == string1
t5 = time.time()
tmp6 = str(b) == string1
t6 = time.time()
times_a[i] = t1 - t0
times_str_a[i] = t2 - t1
times_s[i] = t3 - t2
times_str_s[i] = t4 - t3
times_b[i] = t5 - t4
times_str_b[i] = t6 - t5
print('Small array:')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_a), mean(times_str_a)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_a)/mean(times_a)))
print('\nBig array')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_b), mean(times_str_b)))
print(mean(times_str_b)/mean(times_b))
print('\nString')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_s), mean(times_str_s)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_s)/mean(times_s)))
Result:
Small array:
Time to compare without str conversion: 6.58464431763e-06 s. With str conversion: 0.000173756599426 s
Ratio of time with/without string conversion: 26.3881526541
Big array
Time to compare without str conversion: 5.44309616089e-06 s. With str conversion: 0.000870866775513 s
159.99474375821288
String
Time to compare without str conversion: 5.89370727539e-07 s. With str conversion: 8.30173492432e-07 s
Ratio of time with/without string conversion: 1.40857605178
I see .btn:focus
has an outline
on it:
.btn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
Try changing this to:
.btn:focus {
outline: none !important;
}
Basically, look for any instances of outline
on :focus
ed elements — that's what's causing it.
Update - For Bootstrap v4:
.btn:focus {
box-shadow: none;
}
Are you looking for a particular extension? In your phpinfo();
, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.
Usually in phpinfo()
it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.
Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).
Starting with Version 42, released April 14, 2015, Chrome blocks all NPAPI plugins, including Java. Until September 2015 there will be a way around this, by going to chrome://flags/#enable-npapi
and clicking on Enable
. After that, you will have to use the IE tab extension to run the Direct-X version of the Java plugin.
mercurial_keyring installation on Mac OSX using MacPorts:
sudo port install py-keyring
sudo port install py-mercurial_keyring
Add the following to ~/.hgrc:
# Add your username if you haven't already done so.
[ui]
username = [email protected]
[extensions]
mercurial_keyring =
An angular-only solution that works alongside ng-click
is possible by using compile to wrap the ng-click
expression.
Directive:
.directive('confirmClick', function ($window) {
var i = 0;
return {
restrict: 'A',
priority: 1,
compile: function (tElem, tAttrs) {
var fn = '$$confirmClick' + i++,
_ngClick = tAttrs.ngClick;
tAttrs.ngClick = fn + '($event)';
return function (scope, elem, attrs) {
var confirmMsg = attrs.confirmClick || 'Are you sure?';
scope[fn] = function (event) {
if($window.confirm(confirmMsg)) {
scope.$eval(_ngClick, {$event: event});
}
};
};
}
};
});
HTML:
<a ng-click="doSomething()" confirm-click="Are you sure you wish to proceed?"></a>
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
You should add overflow: hidden
in HTML for a better cross-platform performance.
I would use
html.no-scroll {
overflow: hidden;
}
If you don't mind the slashes being switched, you could [ab]use Uri
:
Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
An excellent explanation can be found here: Generate script in SQL Server Management Studio
Courtesy Ali Issa Here's what you have to do:
If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!
You can use ^ or 0 (Zero) in normal mode to move to the beginning of a line.
^ moves the cursor to the first non-blank character of a line
0 always moves the cursor to the "first column"
You can also use Shifti to move and switch to Insert mode.
Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.
For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.
$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Use the SQL data type CHAR(60)
to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.
Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.
It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX()
function to reduce a string of hex digits by half.
As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.
Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.
response.GetResponseStream()
should be used to return the response stream. And don't forget to close
the Stream
and Response
objects.
Here is an even simplier way, by writing directly to php error output
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, fopen('php://stderr', 'w'));
I solved this on 12.10 by installing libssl-dev.
sudo apt-get install libssl-dev
You can use this nuget package:
Install-Package Xabe.FFmpeg
I'm trying to make easy to use, cross-platform FFmpeg wrapper.
You can find more information about this at Xabe.FFmpeg
More info in documentation
Conversion is simple:
IConversionResult result = await Conversion.ToMp4(Resources.MkvWithAudio, output).Start();
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
You can use a getter, so that your property is going to be reading only. Example:
export class MyClass {
private _LEVELS = {
level1: "level1",
level2: "level2",
level2: "level2"
};
public get STATUSES() {
return this._LEVELS;
}
}
Used in another class:
import { MyClass } from "myclasspath";
class AnotherClass {
private myClass = new MyClass();
tryLevel() {
console.log(this.myClass.STATUSES.level1);
}
}
I know this post is old but...
I was able to do this, my problem was that I forgot to make my property static.
public static class MyStaticClass
{
private static NonStaticObject _myObject = new NonStaticObject();
//property
public static NonStaticObject MyObject
{
get { return _myObject; }
set { _myObject = value; }
}
}
Try this approach using the newer str.format
syntax:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
And here's how to do it using the old %
syntax (useful for older versions of Python that don't support str.format
):
line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
My guess is that you are trying to replace a standard class which ships with Java 5 with one in a library you have.
This is not allowed under the terms of the license agreement, however AFAIK it wasn't enforced until Java 5.
I have seen this with QName before and I "fixed" it by removing the class from the jar I had.
EDIT http://www.manpagez.com/man/1/java/ notes for the option "-Xbootclasspath:"
"Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed as doing so would contravene the Java 2 Runtime Environment binary code license."
The http://www.idt.mdh.se/rc/sumo/aJile/Uppackat/jre/LICENSE
"Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create, additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation."
Assuming that you want to reduce dependencies to other assemblies and to keep things simple, you can do:
var sb = new System.Text.StringBuilder();
sb.Append("a=" + HttpUtility.UrlEncode("TheValueOfA") + "&");
sb.Append("b=" + HttpUtility.UrlEncode("TheValueOfB") + "&");
sb.Append("c=" + HttpUtility.UrlEncode("TheValueOfC") + "&");
sb.Append("d=" + HttpUtility.UrlEncode("TheValueOfD") + "&");
sb.Remove(sb.Length-1, 1); // Remove the final '&'
string result = sb.ToString();
This works well with loops too. The final ampersand removal needs to go outside of the loop.
Note that the concatenation operator is used to improve readability. The cost of using it compared to the cost of using a StringBuilder is minimal (I think Jeff Atwood posted something on this topic).
Include jQuery as usual inside script tags in index.html.
After all the imports but before declaring @Component, add:
declare var $: any;
Now you are free to use jQuery anywhere in your Angular 2 TypeScript code:
$("#myModal").modal('show');
Reference: https://stackoverflow.com/a/38246116/2473022
You can use sed
:
sed 's/^[^ ][^ ]* [^ ][^ ]* //'
This looks for lines starting with one-or-more non-blanks, a blank, another set of one-or-more non-blanks and another blank, and deletes the matched material, aka the first two fields. The [^ ][^ ]*
is marginally shorter than the equivalent but more explicit [^ ]\{1,\}
notation, and the second might run into issues with GNU sed
(though if you use --posix
as an option, even GNU sed
can't screw it up). OTOH, if the character class to be repeated was more complex, the numbered notation wins for brevity. It is easy to extend this to handle 'blank or tab' as separator, or 'multiple blanks' or 'multiple blanks or tabs'. It could also be modified to handle optional leading blanks (or tabs) before the first field, etc.
For awk
and cut
, see Sampson-Chen's answer. There are other ways to write the awk
script, but they're not materially better than the answer given. Note that you might need to set the field separator explicitly (-F" "
) in awk
if you do not want tabs treated as separators, or you might have multiple blanks between fields. The POSIX standard cut
does not support multiple separators between fields; GNU cut
has the useful but non-standard -i
option to allow for multiple separators between fields.
You can also do it in pure shell:
while read junk1 junk2 residue
do echo "$residue"
done < in-file > out-file
It depends on whether you want to know whether it exists in one of the directories in the $PATH
variable or whether you know the absolute location of it. If you want to know if it is in the $PATH
variable, use
if which programname >/dev/null; then
echo exists
else
echo does not exist
fi
otherwise use
if [ -x /path/to/programname ]; then
echo exists
else
echo does not exist
fi
The redirection to /dev/null/
in the first example suppresses the output of the which
program.
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800
At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.
SET @@GLOBAL.wait_timeout=300
After you set the global variable, the session variable automatically grabs the value.
SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300
Next time when the server restarts, the session variables will be set to the default value i.e. 28800.
P.S. I m using MySQL 5.6.16
https://developers.google.com/chrome-developer-tools/docs/settings
Assuming you want no password prompt:
ssh $HOST 'echo $PASSWORD | sudo -S $COMMMAND'
Example
ssh me@localhost 'echo secret | sudo -S echo hi' # outputs 'hi'
This usually works for me:
_x000D_
_x000D_
.parent {_x000D_
min-height: 100px;_x000D_
background-color: green;_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
height: inherit;_x000D_
width: 100%;_x000D_
background-color: red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Suppose your project has the following structure and you want to do imports in the notebook.ipynb
:
/app
/mypackage
mymodule.py
/notebooks
notebook.ipynb
If you are running Jupyter inside a docker container without any virtualenv it might be useful to create Jupyter (ipython) config in your project folder:
/app
/profile_default
ipython_config.py
Content of ipython_config.py
:
c.InteractiveShellApp.exec_lines = [
'import sys; sys.path.append("/app")'
]
Open the notebook and check it out:
print(sys.path)
['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/IPython/extensions', '/root/.ipython', '/app']
Now you can do imports in your notebook without any sys.path
appending in the cells:
from mypackage.mymodule import myfunc
According to size_t description on en.cppreference.com size_t
is defined in the following headers :
std::size_t
...
Defined in header <cstddef>
Defined in header <cstdio>
Defined in header <cstring>
Defined in header <ctime>
Defined in header <cwchar>
yield
?The yield
keyword returns data from a generator function:
The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
A generator function is effectively a more compact and efficient way to write an Iterator. It allows you to define a function (your xrange
) that will calculate and return values while you are looping over it:
function xrange($min, $max) {
for ($i = $min; $i <= $max; $i++) {
yield $i;
}
}
[…]
foreach (xrange(1, 10) as $key => $value) {
echo "$key => $value", PHP_EOL;
}
This would create the following output:
0 => 1
1 => 2
…
9 => 10
You can also control the $key
in the foreach
by using
yield $someKey => $someValue;
In the generator function, $someKey
is whatever you want appear for $key
and $someValue
being the value in $val
. In the question's example that's $i
.
Now you might wonder why we are not simply using PHP's native range
function to achieve that output. And right you are. The output would be the same. The difference is how we got there.
When we use range
PHP, will execute it, create the entire array of numbers in memory and return
that entire array to the foreach
loop which will then go over it and output the values. In other words, the foreach
will operate on the array itself. The range
function and the foreach
only "talk" once. Think of it like getting a package in the mail. The delivery guy will hand you the package and leave. And then you unwrap the entire package, taking out whatever is in there.
When we use the generator function, PHP will step into the function and execute it until it either meets the end or a yield
keyword. When it meets a yield
, it will then return whatever is the value at that time to the outer loop. Then it goes back into the generator function and continues from where it yielded. Since your xrange
holds a for
loop, it will execute and yield until $max
was reached. Think of it like the foreach
and the generator playing ping pong.
Obviously, generators can be used to work around memory limits. Depending on your environment, doing a range(1, 1000000)
will fatal your script whereas the same with a generator will just work fine. Or as Wikipedia puts it:
Because generators compute their yielded values only on demand, they are useful for representing sequences that would be expensive or impossible to compute at once. These include e.g. infinite sequences and live data streams.
Generators are also supposed to be pretty fast. But keep in mind that when we are talking about fast, we are usually talking in very small numbers. So before you now run off and change all your code to use generators, do a benchmark to see where it makes sense.
Another Use Case for Generators is asynchronous coroutines. The yield
keyword does not only return values but it also accepts them. For details on this, see the two excellent blog posts linked below.
yield
?Generators have been introduced in PHP 5.5. Trying to use yield
before that version will result in various parse errors, depending on the code that follows the keyword. So if you get a parse error from that code, update your PHP.
See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:
shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"
It seems that you need to pass a flag "-l, --log-file"
https://github.com/elastic/kibana/issues/3407
Usage: kibana [options]
Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.
Options:
-h, --help output usage information
-V, --version output the version number
-e, --elasticsearch <uri> Elasticsearch instance
-c, --config <path> Path to the config file
-p, --port <port> The port to bind to
-q, --quiet Turns off logging
-H, --host <host> The host to bind to
-l, --log-file <path> The file to log to
--plugins <path> Path to scan for plugins
If you use the init script to run as a service, maybe you will need to customize it.
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
I had the same problem when using bootstrap-datewidget and i loaded jquery in the header instead of loading it at the end of the body and it worked.
The simplest solution would be to use Pillow lib:
from PIL import Image
image = Image.fromarray(<your_numpy_array>.astype(np.uint8))
And you can use it as an image.
Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
in VB you can use this one
Dim selectedRow As DataRowView
selectedRow = dg.Rows(dg.CurrentCell.RowIndex).DataBoundItem
selectedRow("MyProp") = "myValue"
dg.NotifyCurrentCellDirty(True)
thanks to saeed serpooshan for last row
While the accepted answer is right that you can inject Math
to use it in angular, for this particular problem, the more conventional/angular way is the number filter:
<p>The percentage is {{(100*count/total)| number:0}}%</p>
You can read more about the number
filter here: http://docs.angularjs.org/api/ng/filter/number
Depends also on what flags are required to open. With respect to usage for writing and reading (and portability) f* should be used, as argued above.
But if basically want to specify more than standard flags (like rw and append flags), you will have to use a platform specific API (like POSIX open) or a library that abstracts these details. The C-standard does not have any such flags.
For example you might want to open a file, only if it exits. If you don't specify the create flag the file must exist. If you add exclusive to create, it will only create the file if it does not exist. There are many more.
For example on Linux systems there is a LED interface exposed through sysfs. It exposes the brightness of the led through a file. Writing or reading a number as a string ranging from 0-255. Of course you don't want to create that file and only write to it if it exists. The cool thing now: Use fdopen to read/write this file using the standard calls.
I did using in-app updates. This will only with devices running Android 5.0 (API level 21) or higher,
Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
There is a function UTC()
that returns the milliseconds from the unix epoch.
Since the values are actually inside of an HTML attribute, you should use '
"<img src='something' onmouseover='change('ex1')' />";
Simple seven step to solve issue in case of WampServer:
Execute Statement
SET PASSWORD FOR root@localhost=PASSWORD('root');
open D:\wamp\apps\phpmyadmin4.1.14\config.inc.php file set value
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
Restart All services
HTML
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="main_body">
some text
</div>
</body>
</html>
CSS
body
{
width: 100%;
Height: 100%;
}
#main_body
{
background: #ff3333;
width: 200px;
position: absolute;
}?
JS ( jQuery )
$(function(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var main = $("#main_body");
$("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});
See example here
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.
Make sure the form KeyPreview property is set to true.
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
SendKeys.Send("{TAB}")
e.Handled = True
End If
End Sub
<activity android:name="[packagename optional].ActivityClassName"></activity>
Simply adding the activity which we want to switch to should be placed in the manifest file