ObjectID
s are objects so if you just compare them with ==
you're comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
By default it will be hidden in your home directory. Type ls -a ~
to view that.
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
you don't - not like this. give an id to your tag , lets say it looks like this now :
<h3 id="myHeader"></h3>
then set the value like that :
myHeader.innerText = "public offers";
It's not smart to have python code inside java. Wrap your python code with flask or other web framework to make it as a microservice. Make your java program able to call this microservice (e.g. via REST).
Beleive me, this is much simple and will save you tons of issues. And the codes are loosely coupled so they are scalable.
Updated on Mar 24th 2020: According to @stx's comment, the above approach is not suitable for massive data transfer between client and server. Here is another approach I recommended: Connecting Python and Java with Rust(C/C++ also ok). https://medium.com/@shmulikamar/https-medium-com-shmulikamar-connecting-python-and-java-with-rust-11c256a1dfb0
simplest way(and even works from api 1) that tested is:
getResources().getDimensionPixelSize(R.dimen.example_dimen);
From documentations:
Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.
Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.
I know this is a bit old but I think there might be a much simpler solution that requires no additional coding:
Instead of transposing, redimming and transposing again, and if we talk about a two dimensional array, why not just store the values transposed to begin with. In that case redim preserve actually increases the right (second) dimension from the start. Or in other words, to visualise it, why not store in two rows instead of two columns if only the nr of columns can be increased with redim preserve.
the indexes would than be 00-01, 01-11, 02-12, 03-13, 04-14, 05-15 ... 0 25-1 25 etcetera instead of 00-01, 10-11, 20-21, 30-31, 40-41 etcetera.
As long as there is only one dimension that needs to be redimmed-preserved the approach would still work: just put that dimension last.
As only the second (or last) dimension can be preserved while redimming, one could maybe argue that this is how arrays are supposed to be used to begin with. I have not seen this solution anywhere so maybe I'm overlooking something?
(Posted earlier on similar question regarding two dimensions, extended answer here for more dimensions)
I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.
function insertUrlParam(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
I need to know if they have difference in one of their nested properties
Other answers provide potentially satisfactory solutions to this problem, but it is sufficiently difficult and common that it looks like there's a very popular package to help solve this issue deep-object-diff.
To use this package you'd need to npm i deep-object-diff
then:
const { diff } = require('deep-object-diff');
var a = {};
var b = {};
a.prop1 = 2;
a.prop2 = { prop3: 2 };
b.prop1 = 2;
b.prop2 = { prop3: 3 };
if (!_.isEqual(a, b)) {
const abDiff = diff(a, b);
console.log(abDiff);
/*
{
prop2: {
prop3: 3
}
}
*/
}
// or alternatively
const abDiff = diff(a, b);
if(!_.isEmpty(abDiff)) {
// if a diff exists then they aren't deeply equal
// perform needed actions with diff...
}
Here's a more detailed case with property deletions directly from their docs:
const lhs = {
foo: {
bar: {
a: ['a', 'b'],
b: 2,
c: ['x', 'y'],
e: 100 // deleted
}
},
buzz: 'world'
};
const rhs = {
foo: {
bar: {
a: ['a'], // index 1 ('b') deleted
b: 2, // unchanged
c: ['x', 'y', 'z'], // 'z' added
d: 'Hello, world!' // added
}
},
buzz: 'fizz' // updated
};
console.log(diff(lhs, rhs)); // =>
/*
{
foo: {
bar: {
a: {
'1': undefined
},
c: {
'2': 'z'
},
d: 'Hello, world!',
e: undefined
}
},
buzz: 'fizz'
}
*/
For implementation details and other usage info, refer to that repo.
You could use with open("path") as file:
so that it automatically closes, else if it's open in another process you can maybe try
as in Tims example you should use except IOError to not ignore any other problem with your code :)
try:
with open("path", "r") as file: # or just open
# Code here
except IOError:
# raise error or print
What about a private method that simply looks for the element and determines if it is present like this:
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
This would be quite easy and does the job.
Edit: you could even go further and take a By elementLocator
as parameter, eliminating problems if you want to find the element by something other than id.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:
DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '
SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT name
FROM sysobjects
WHERE xtype = 'PK'
AND parent_obj = OBJECT_ID('Student')))
EXEC (@SQL)
This is a simple way to call notification by using default vibrate and sound from system.
private void sendNotification(String message, String tick, String title, boolean sound, boolean vibrate, int iconID) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Notification notification = new Notification();
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
if (sound) {
notification.defaults |= Notification.DEFAULT_SOUND;
}
if (vibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
notificationBuilder.setDefaults(notification.defaults);
notificationBuilder.setSmallIcon(iconID)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setTicker(tick)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Add vibrate permission if you are going to use it:
<uses-permission android:name="android.permission.VIBRATE"/>
Good luck,'.
You can plot several columns at once by supplying a list of column names to the plot
's y
argument.
df.plot(x="X", y=["A", "B", "C"], kind="bar")
This will produce a graph where bars are sitting next to each other.
In order to have them overlapping, you would need to call plot
several times, and supplying the axes to plot to as an argument ax
to the plot.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])
ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")
plt.show()
This worked perfect for me.
Double legacyRow = row.getCell(col).getNumericCellValue();
String legacyRowStr = legacyRow.toString();
if(legacyRowStr.contains(".0")){
legacyRowStr = legacyRowStr.substring(0, legacyRowStr.length()-2);
}
The syntax is wrong, it should instead be
svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>
I faced same issue on Linux when I installed docker using yum (yum install docker).
Resolution: download docker binary from official site: docker install, unpack and follow the installation steps.
The previous answers all give $_SERVER['SERVER_ADDR']. This will not work on some IIS installations. If you want this to work on IIS, then use the following:
$server_ip = gethostbyname($_SERVER['SERVER_NAME']);
Just use crontab -e
and follow the tutorial here.
Look at point 3 for a guide on how to specify the frequency.
Based on your requirement, it should effectively be:
*/10 * * * * /usr/bin/python script.py
you can use Glide for load and transform into blur image, 1) for only one view,
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view)
2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.
if(isBlure){
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50))
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view )
}else{
val requestOptions = RequestOptions()
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}
If you have a small database and you want to version the entire thing, this batch script might help. It detaches, compresses, and checks a MSSQL database MDF file in to Subversion.
If you mostly want to version your schema and just have a small amount of reference data, you can possibly use SubSonic Migrations to handle that. The benefit there is that you can easily migrate up or down to any specific version.
This is a linker issue. Try:
g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`
This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:
sudo ldconfig
private static ISheet GetFileStream(string fullFilePath)
{
var fileExtension = Path.GetExtension(fullFilePath);
string sheetName;
ISheet sheet = null;
switch (fileExtension)
{
case ".xlsx":
using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
{
var wb = new XSSFWorkbook(fs);
sheetName = wb.GetSheetAt(0).SheetName;
sheet = (XSSFSheet) wb.GetSheet(sheetName);
}
break;
case ".xls":
using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read))
{
var wb = new HSSFWorkbook(fs);
sheetName = wb.GetSheetAt(0).SheetName;
sheet = (HSSFSheet) wb.GetSheet(sheetName);
}
break;
}
return sheet;
}
private static DataTable GetRequestsDataFromExcel(string fullFilePath)
{
try
{
var sh = GetFileStream(fullFilePath);
var dtExcelTable = new DataTable();
dtExcelTable.Rows.Clear();
dtExcelTable.Columns.Clear();
var headerRow = sh.GetRow(0);
int colCount = headerRow.LastCellNum;
for (var c = 0; c < colCount; c++)
dtExcelTable.Columns.Add(headerRow.GetCell(c).ToString());
var i = 1;
var currentRow = sh.GetRow(i);
while (currentRow != null)
{
var dr = dtExcelTable.NewRow();
for (var j = 0; j < currentRow.Cells.Count; j++)
{
var cell = currentRow.GetCell(j);
if (cell != null)
switch (cell.CellType)
{
case CellType.Numeric:
dr[j] = DateUtil.IsCellDateFormatted(cell)
? cell.DateCellValue.ToString(CultureInfo.InvariantCulture)
: cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
break;
case CellType.String:
dr[j] = cell.StringCellValue;
break;
case CellType.Blank:
dr[j] = string.Empty;
break;
}
}
dtExcelTable.Rows.Add(dr);
i++;
currentRow = sh.GetRow(i);
}
return dtExcelTable;
}
catch (Exception e)
{
throw;
}
}
You should update the "Microsoft.CodeDom.Providers.DotNetCompilerPlatform" and "Microsoft.Net.Compilers" packages in your project .
I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.
<ComboBox Name="CategoryList"
DisplayMemberPath="CategoryName"
SelectedItem="{Binding Path=CategoryParent}"
SelectedValue="{Binding Path=CategoryParent.ID}"
SelectedValuePath="ID">
See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.
This works with our libraries running GIT v1.7.1, where we have a DEV package repo and LIVE package repo. The repositories themselves are nothing but a shell to package the assets for a project. all submodules.
The LIVE is never updated intentionally, however cache files or accidents can occur, leaving the repo dirty. New submodules added to the DEV must be initialized within LIVE as well.
Package Repository in DEV
Here we want to pull all upstream changes that we are not yet aware of, then we will update our package repository.
# Recursively reset to the last HEAD
git submodule foreach --recursive git reset --hard
# Recursively cleanup all files and directories
git submodule foreach --recursive git clean -fd
# Recursively pull the upstream master
git submodule foreach --recursive git pull origin master
# Add / Commit / Push all updates to the package repo
git add .
git commit -m "Updates submodules"
git push
Package Repository in LIVE
Here we want to pull the changes that are committed to the DEV repository, but not unknown upstream changes.
# Pull changes
git pull
# Pull status (this is required for the submodule update to work)
git status
# Initialize / Update
git submodule update --init --recursive
Other way to solve the problem of space reclaiming is, Create multiple partitions within table - Range based, Value based partitions and just drop/truncate the partition to reclaim the space, which will release the space used by whole data stored in the particular partition.
There will be some changes needed in table schema when you introduce the partitioning for your table like - Unique Keys, Indexes to include partition column etc.
after some test: If you send an email to an outlook client, and the subject is >77 chars, and it needs to use "=?ISO"
inside the subject (in my case because of accents) then OutLook will "cut" the subject in the middle of it and mesh it all that comes after, including body text, attaches, etc... all a mesh!
I have several examples like this one:
Subject: =?ISO-8859-1?Q?Actas de la obra N=BA.20100154 (Expediente N=BA.20100182) "NUEVA RED FERROVIARIA.=
TRAMO=20BEASAIN=20OESTE(Pedido=20PC10/00123-125),=20BEASAIN".?=
To:
As you see, in the subject line it cutted on char 78 with a "=" followed by 2 or 3 line feeds, then continued with the rest of the subject baddly.
It was reported to me from several customers who all where using OutLook, other email clients deal with those subjects ok.
If you have no ISO on it, it doesn't hurt, but if you add it to your subject to be nice to RFC, then you get this surprise from OutLook. Bit if you don't add the ISOs, then iPhone email will not understand it(and attach files with names using such characters will not work on iPhones).
linear, almost-purely-functional-approach
var min=[0, 29, 25].map((function(max) {max=-Infinity; return function(e) {return max=Math.max(max, e);}})())[0]
More examples:
Finding out min value
function getMin(arr) {
return (ar || [0, 29, 25]).
map((function(max) {max=-Infinity; return function(e) {return max=Math.max(max, e);}})())[0];
}
or using Array.map
method with variable closuring
function getMin(arrObjs) {
return (arrObjs || [{val: 0}, {val: 29}, {val: 25}]).
map((function(max) {max=-Infinity; return function(e) {return max=(max.val>e.val?max:e);}})())[0];
}
Finding out max value
function getMax(arr) {
return (ar || [0, 29, 25]).
map((function(v) {v=Infinity; return function(e) {return v=Math.min(v, e);}})())[0];
}
for array of objects
function getMax(arrObjs) {
return (arrObjs || [{val: 0}, {val: 29}, {val: 25}]).
map((function(v) {v=-Infinity; return function(e) {return v=(v.val<e.val?v:e);}})())[0];
}
No, TRUNCATE
is all or nothing. You can do a DELETE FROM <table> WHERE <conditions>
but this loses the speed advantages of TRUNCATE
.
An alternative way to rename files using the renamer npm package.
below is an example of renaming files extensions
renamer -d --path-element ext --find ts --replace js *
For %d
part refer to this How does this program work? and for decimal places use %.2f
Using the latest 1.0.6
version of Socket.IO
and have my app deployed on Heroku
, I get the client IP
and port
using the headers
into the socket handshake
:
var socketio = require('socket.io').listen(server);
socketio.on('connection', function(socket) {
var sHeaders = socket.handshake.headers;
console.info('[%s:%s] CONNECT', sHeaders['x-forwarded-for'], sHeaders['x-forwarded-port']);
}
I found the following pattern to work well for me in code where I want to show a dialog to get the input (e.g., the string displayed in the text field is the result of selections made from a list of checkboxes in a dialog, rather than text entered via the keyboard).
Initial clicks in the text field yield a focus change, a repeated click yields a click event. So I override both (here I don't refactor the code out to illustrate both handlers do the same thing):
tx = (TextView) m_activity.findViewById(R.id.allergymeds);
if (tx != null) {
tx.setShowSoftInputOnFocus(false);
tx.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
MedicationsListDialogFragment mld = new MedicationsListDialogFragment();
mld.setPatientId(m_sess.getActivePatientId());
mld.show(getFragmentManager(), "Allergy Medications Dialog");
}
}
});
tx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MedicationsListDialogFragment mld = new MedicationsListDialogFragment();
mld.setPatientId(m_sess.getActivePatientId());
mld.show(getFragmentManager(), "Allergy Medications Dialog");
}
});
}
Markdown is a plain-text file format. The extensions .md
and .markdown
are just text files written in Markdown syntax. If you have a Readme.md
in your repo, GitHub will show the contents on the home page of your repo. Read the documentation:
You can edit the Readme.md
file in GitHub itself. Click on Readme.md, you will find an edit button. You can preview your changes and even commit them from there.
Since it is a text file, Notepad or Notepad++ (Windows), TextEdit (Mac) or any other text editor can be used to edit and modify it. Specialized editors exist that automatically parse the markdown as you type it and generate a preview, while others apply various syntax coloring and decorations to the displayed text. In both cases though, the saved file is still a readable text file.
If you want to create an md
file with preview and if you prefer not to install any special editors, you can use online editors like dillinger.io and stackedit.io. They provide live preview. You can also export your files to Google Drive or Dropbox.
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
render();
}
window.addEventListener('resize', resize, false); resize();
function render() { // draw to screen here
}
I was getting this error as well.
I was using:
import BrowserRouter from 'react-router-dom';
Fix was doing this, instead:
import { BrowserRouter } from 'react-router-dom';
Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.
span.gbp {_x000D_
float: left;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
float: left;_x000D_
content: "\00a3"; /* £ */_x000D_
padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
<input type="number" placeholder="Enter whole GBP (£) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.
I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?
Based on your comments to orip's post, I guess this is what happened:
__init__.py
on windows.__init__.py
(now called __init__.py.bin
) means python doesn't understand toolkit as a package.__init__.py
in the appropriate directory and everything works... ?Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer
C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks()
method to it, in particular, to do exactly what you require).
On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer
, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).
Set the CommandText
as well, and call Fill
on the SqlAdapter
to retrieve the results in a DataSet
:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
For me, I did mvn clean
and then restart the tomcat. It worked for me
This one is just extension of article you found.
public class WebClientEx : WebClient
{
public WebClientEx(CookieContainer container)
{
this.container = container;
}
public CookieContainer CookieContainer
{
get { return container; }
set { container= value; }
}
private CookieContainer container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest r = base.GetWebRequest(address);
var request = r as HttpWebRequest;
if (request != null)
{
request.CookieContainer = container;
}
return r;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = base.GetWebResponse(request, result);
ReadCookies(response);
return response;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
ReadCookies(response);
return response;
}
private void ReadCookies(WebResponse r)
{
var response = r as HttpWebResponse;
if (response != null)
{
CookieCollection cookies = response.Cookies;
container.Add(cookies);
}
}
}
You need to add a metadata exchange (mex) endpoint to your service:
<services>
<service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
<endpoint
address="http://localhost/MyService.svc"
binding="customBinding" bindingConfiguration="jsonpBinding"
behaviorConfiguration="MyService.MyService"
contract="MyService.IMyService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
Now, you should be able to get metadata for your service
Update: ok, so you're just launching this from Visual Studio - in that case, it will be hosted in Cassini, the built-in web server. That beast however only supports HTTP - you're not using that protocol in your binding...
Also, since you're hosting this in Cassini, the address of your service will be dictated by Cassini - you don't get to define anything.
So my suggestion would be:
So I would change the config to:
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
<endpoint
address="" <!-- don't put anything here - Cassini will determine address -->
binding="basicHttpBinding"
contract="MyService.IMyService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
Once you have that, try to do a View in Browser
on your SVC file in your Visual Studio solution - if that doesn't work, you still have a major problem of some sort.
If it works - now you can press F5 in VS and your service should come up, and using the WCF Test Client app, you should be able to get your service metadata from a) the address that Cassini started your service on, or b) the mex address (Cassini's address + /mex
)
In the case where the process was spawned by another node process, like:
var child = spawn('gulp', ['watch'], {
stdio: 'inherit',
});
And you try to kill it later, via:
child.kill();
This is how you handle the event [on the child]:
process.on('SIGTERM', function() {
console.log('Goodbye!');
});
I had the same problem, after some Windows 8.0 crash and update, on msys git 1.9. I didn't find any msys/git in my path, so I just added it in windows local-user envinroment settings. It worked without restarting.
Basically, similiar to RobertB, but I didn't have any git/msys in my path.
Btw:
I tried using rebase -b blablabla msys.dll, but had error "ReBaseImage (msys-1.0.dll) failed with last error = 6"
if you need this quickly and don't have time debugging, I noticed "Git Bash.vbs" in Git directory successfuly starts bash shell.
The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.
To take picture from camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)
To pick photo from gallery:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
onActivityResult
code:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageview.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageview.setImageURI(selectedImage);
}
break;
}
}
Finally add this permission in the manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
you can use simply write the code in a .bat
format extension ,the code of the batch file :
c:/ copy /b Image1.jpg + Archive.rar Image2.jpg
use this c# code :
Process.Start("file_name.bat")
You could use a Bash C Style For Loop to do what you want.
my_array=(one two three)
for ((i=0; i < ${#my_array[@]}; i++ )); do echo "${my_array[$i]}"; done
one
two
three
error reason running mysql in XAMPP server in win8 thats hapen for me.
if error display when you install MariaDB First Stop MySql in XAMPP
and install MariaDB there is not problem now...have a nice day...
Using ant debug after building build.xml file :
in your cmd your root should be your project at first then use the ant debug command e.g:
c:\testApp>ant debug
@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this
[{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map( ( {name, email} ) => {
return <p key={email}>{name} - {email}</p>
})
Cheers!
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
Another approach is to first do a searchType: 'count'
, then and then do a normal search with size
set to results.count
.
The advantage here is it avoids depending on a magic number for UPPER_BOUND
as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan
.
The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.
<video id="myvideo">
<source src="path/to/movie.mp4" />
</video>
<p onclick="toggleControls();">Toggle</p>
<script>
var video = document.getElementById("myvideo");
function toggleControls() {
if (video.hasAttribute("controls")) {
video.removeAttribute("controls")
} else {
video.setAttribute("controls","controls")
}
}
</script>
See it working on jsFiddle: http://jsfiddle.net/dgLds/
This also happens to me when I try to install the opencv-python
package:
I can fix it with command line
python3 -m pip install {name of package} --user
When I try to install the said package, the command becomes:
python3 -m pip install opencv-python --user
Resulting in this:
Use explicit injection. No other approach will allow you for instance to run tests in parallel in the same JVM.
Patterns that use anything classloader wide like static log binder or messing with environmental thinks like logback.XML are bust when it comes to testing.
Consider the parallelized tests I mention , or consider the case where you want to intercept logging of component A whose construction is hidden behind api B. This latter case is easy to deal with if you are using a dependency injected loggerfactory from the top, but not if you inject Logger as there no seam in this assembly at ILoggerFactory.getLogger.
And its not all about unit testing either. Sometimes we want integration tests to emit logging. Sometimes we don't. Someone's we want some of the integration testing logging to be selectively suppressed, eg for expected errors that would otherwise clutter the CI console and confuse. All easy if you inject ILoggerFactory from the top of your mainline (or whatever di framework you might use)
So...
Either inject a reporter as suggested or adopt a pattern of injecting the ILoggerFactory. By explicit ILoggerFactory injection rather than Logger you can support many access/intercept patterns and parallelization.
I believe this is efficient enough... To get a String from an InputStream, I'd call the following method:
public static String getStringFromInputStream(InputStream stream) throws IOException
{
int n = 0;
char[] buffer = new char[1024 * 4];
InputStreamReader reader = new InputStreamReader(stream, "UTF8");
StringWriter writer = new StringWriter();
while (-1 != (n = reader.read(buffer))) writer.write(buffer, 0, n);
return writer.toString();
}
I always use UTF-8. You could, of course, set charset as an argument, besides InputStream.
I think you just need to remove the space. i.e.
$(".myclass[reference=12345]").css('border', '#000 solid 1px');
There is a fiddle here http://jsfiddle.net/xXEHY/
All the above are good. This one seems really simple to me and easy to understand. Excuse the quotes. I wrote it for Groovy inside a class called DataCenter.
static String extractDomainName(String url) {
int start = url.indexOf('://')
if (start < 0) {
start = 0
} else {
start += 3
}
int end = url.indexOf('/', start)
if (end < 0) {
end = url.length()
}
String domainName = url.substring(start, end)
int port = domainName.indexOf(':')
if (port >= 0) {
domainName = domainName.substring(0, port)
}
domainName
}
And here are some junit4 tests:
@Test
void shouldFindDomainName() {
assert DataCenter.extractDomainName('http://example.com/path/') == 'example.com'
assert DataCenter.extractDomainName('http://subpart.example.com/path/') == 'subpart.example.com'
assert DataCenter.extractDomainName('http://example.com') == 'example.com'
assert DataCenter.extractDomainName('http://example.com:18445/path/') == 'example.com'
assert DataCenter.extractDomainName('example.com/path/') == 'example.com'
assert DataCenter.extractDomainName('example.com') == 'example.com'
}
$("#ddlMultiselect").val('').trigger("change");
for multi-select drop-down, it will clear displayed text.
This worked for me in Xamarin.iOS / Monotouch. Change the keyboard button to Next, pass the control to the next UITextField and hide the keyboard after the last UITextField.
private void SetShouldReturnDelegates(IEnumerable<UIView> subViewsToScout )
{
foreach (var item in subViewsToScout.Where(item => item.GetType() == typeof (UITextField)))
{
(item as UITextField).ReturnKeyType = UIReturnKeyType.Next;
(item as UITextField).ShouldReturn += (textField) =>
{
nint nextTag = textField.Tag + 1;
var nextResponder = textField.Superview.ViewWithTag(nextTag);
if (null != nextResponder)
nextResponder.BecomeFirstResponder();
else
textField.Superview.EndEditing(true);
//You could also use textField.ResignFirstResponder();
return false; // We do not want UITextField to insert line-breaks.
};
}
}
Inside the ViewDidLoad you'll have:
If your TextFields haven't a Tag set it now:
txtField1.Tag = 0;
txtField2.Tag = 1;
txtField3.Tag = 2;
//...
and just the call
SetShouldReturnDelegates(yourViewWithTxtFields.Subviews.ToList());
//If you are not sure of which view contains your fields you can also call it in a safer way:
SetShouldReturnDelegates(txtField1.Superview.Subviews.ToList());
//You can also reuse the same method with different containerViews in case your UITextField are under different views.
To configure Sublime to always use tabs try the adding the following to preferences->settings-user:
{
"tab_size": 4,
"translate_tabs_to_spaces": false
}
More information here: http://www.sublimetext.com/docs/2/indentation.html
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:
function compute() {
if ( $('input[name=type]:checked').val() != undefined ) {
var a = parseInt($('input[name=service_price]').val());
var b = parseInt($('input[name=modem_price]').val());
var total = a+b;
$('#total_price').val(a+b);
}
}
and this should work.
Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.
CSRF can be enforced at the view level, which can't be disabled globally.
In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.
https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps
Nobody mentioned:
@Override
protected void onCreate(Bundle savedInstanceState) {
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
}
OK,
One of the more difficult concepts to grasp about Excel VSTO programming is that you don't refer to cells like an array, Worksheet[0][0]
won't give you cell A1, it will error out on you. Even when you type into A1 when Excel is open, you are actually entering data into Range A1. Therefore you refer to cells as Named Ranges. Here's an example:
Excel.Worksheet sheet = workbook.Sheets["Sheet1"] as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", Missing.Value)
You can now literally type:
range.Text // this will give you the text the user sees
range.Value2 // this will give you the actual value stored by Excel (without rounding)
If you want to do something like this:
Excel.Range range = sheet.get_Range("A1:A5", Missing.Value)
if (range1 != null)
foreach (Excel.Range r in range1)
{
string user = r.Text
string value = r.Value2
}
There might be a better way, but this has worked for me.
The reason you need to use Value2
and not Value
is because the Value
property is a parametrized and C# doesn't support them yet.
As for the cleanup code, i will post that when i get to work tomorrow, i don't have the code with me, but it's very boilerplate. You just close and release the objects in the reverse order you created them. You can't use a Using()
block because the Excel.Application or Excel.Workbook doesn't implement IDisposable
, and if you don't clean-up, you will be left with a hanging Excel objects in memory.
Note:
Visibility
property Excel doesn't display, which can be disconcerting to your users, but if you want to just rip the data out, that is probably good enoughI hope that gets you started, let me know if you need further clarification. I'll post a complete
here is a complete sample:
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using ExcelTools = Ms.Office;
using Excel = Microsoft.Office.Interop.Excel;
namespace Tests
{
[TestFixture]
public class ExcelSingle
{
[Test]
public void ProcessWorkbook()
{
string file = @"C:\Users\Chris\Desktop\TestSheet.xls";
Console.WriteLine(file);
Excel.Application excel = null;
Excel.Workbook wkb = null;
try
{
excel = new Excel.Application();
wkb = ExcelTools.OfficeUtil.OpenBook(excel, file);
Excel.Worksheet sheet = wkb.Sheets["Data"] as Excel.Worksheet;
Excel.Range range = null;
if (sheet != null)
range = sheet.get_Range("A1", Missing.Value);
string A1 = String.Empty;
if( range != null )
A1 = range.Text.ToString();
Console.WriteLine("A1 value: {0}", A1);
}
catch(Exception ex)
{
//if you need to handle stuff
Console.WriteLine(ex.Message);
}
finally
{
if (wkb != null)
ExcelTools.OfficeUtil.ReleaseRCM(wkb);
if (excel != null)
ExcelTools.OfficeUtil.ReleaseRCM(excel);
}
}
}
}
I'll post the functions from ExcelTools tomorrow, I don't have that code with me either.
Edit: As promised, here are the Functions from ExcelTools you might need.
public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly, bool editable,
bool updateLinks) {
Excel.Workbook book = excelInstance.Workbooks.Open(
fileName, updateLinks, readOnly,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
return book;
}
public static void ReleaseRCM(object o) {
try {
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
} catch {
} finally {
o = null;
}
}
To be frank, this stuff is much easier if you use VB.NET. It's in C# because I didn't write it. VB.NET does option parameters well, C# does not, hence the Type.Missing. Once you typed Type.Missing twice in a row, you run screaming from the room!
As for you question, you can try to following:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.find(VS.80).aspx
I will post an example when I get back from my meeting... cheers
Edit: Here is an example
range = sheet.Cells.Find("Value to Find",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Excel.XlSearchDirection.xlNext,
Type.Missing,
Type.Missing, Type.Missing);
range.Text; //give you the value found
Here is another example inspired by this site:
range = sheet.Cells.Find("Value to find", Type.Missing, Type.Missing,Excel.XlLookAt.xlWhole,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,false, false, Type.Missing);
It helps to understand the parameters.
P.S. I'm one of those weird people who enjoys learning COM automation. All this code steamed from a tool I wrote for work which required me to process over 1000+ spreadsheets from the lab each Monday.
I'm using cyanogenmod 7.2 on android 2.3.4, then just open terminal emulator and type:
$ ip addr show
$ ip route show
If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.
For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.
Note that with the above code you can't attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.
Note that for "Untitled" editor ("Untitled-1
", "Untitled-2
"), you now can set the language in the settings.
The previous setting was:
"files.associations": {
"untitled-*": "javascript"
}
This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-
"
See "Untitled editor improvements"
Regarding the associated language for those "Untitled" editors:
By default, untitled files do not have a specific language mode configured.
VS Code has a setting,
files.defaultLanguage
, to configure a default language for untitled files.With this release, the setting can take a new value
{activeEditorLanguage}
that will dynamically use the language mode of the currently active editor instead of a fixed default.In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:
And see workbench.editor.untitled.labelFormat
in VSCode 1.43.
Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.
>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}
#include<stdio.h>
#define n 3
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
struct body bodies[n];
int main()
{
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
return 0;
}
this works fine. your question was not very clear by the way, so match the layout of your source code with the above.
A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.
IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).
A Double
in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double
object.
use MD5
,
$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
but MD5
is insecure. Use SHA2
.
Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 }
is an idiomatic universal zero-initializer. This is also almost the case in C++.
Since this initalizer is universal, for bool
array you don't really need a different "syntax". 0
works as an initializer for bool
type as well, so
bool myBoolArray[ARRAY_SIZE] = { 0 };
is guaranteed to initialize the entire array with false
. As well as
char* myPtrArray[ARRAY_SIZE] = { 0 };
in guaranteed to initialize the whole array with null-pointers of type char *
.
If you believe it improves readability, you can certainly use
bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };
but the point is that = { 0 }
variant gives you exactly the same result.
However, in C++ = { 0 }
might not work for all types, like enum types, for example, which cannot be initialized with integral 0
. But C++ supports the shorter form
T myArray[ARRAY_SIZE] = {};
i.e. just an empty pair of {}
. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.
$(window).keypress("c", function(e) {
if (!e.ctrlKey)
return;
console.info("CTRL + C detected !");
});
$(window).keypress("c", function(e) {_x000D_
if (!e.ctrlKey)_x000D_
return;_x000D_
_x000D_
$("div").show();_x000D_
});
_x000D_
/*https://gist.github.com/jeromyanglim/3952143 */_x000D_
_x000D_
kbd {_x000D_
white-space: nowrap;_x000D_
color: #000;_x000D_
background: #eee;_x000D_
border-style: solid;_x000D_
border-color: #ccc #aaa #888 #bbb;_x000D_
padding: 2px 6px;_x000D_
-moz-border-radius: 4px;_x000D_
-webkit-border-radius: 4px;_x000D_
border-radius: 4px;_x000D_
-moz-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;_x000D_
-webkit-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;_x000D_
box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;_x000D_
background-color: #FAFAFA;_x000D_
border-color: #CCCCCC #CCCCCC #FFFFFF;_x000D_
border-style: solid solid none;_x000D_
border-width: 1px 1px medium;_x000D_
color: #444444;_x000D_
font-family: 'Helvetica Neue', Helvetica, Arial, Sans-serif;_x000D_
font-size: 11px;_x000D_
font-weight: bold;_x000D_
white-space: nowrap;_x000D_
display: inline-block;_x000D_
margin-bottom: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div style="display:none">_x000D_
<kbd>CTRL</kbd> + <kbd>C</kbd> detected !_x000D_
</div>
_x000D_
I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/
Internal classes need to be tested and there is an assemby attribute:
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("MyTests")]
Add this to the project info file, e.g. Properties\AssemblyInfo.cs
.
Use Apache Commons Lang:
String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);
or with standalone JDK:
String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);
The final outcome of the conversion is that the number of elements in the final array is same as that of the initial array or data frame.
-1 corresponds to the unknown count of the row or column.
We can think of it as x
(unknown). x
is obtained by dividing the number of elements in the original array by the other value of the ordered pair with -1.
Examples:
12 elements with reshape(-1,1)
corresponds to an array with x
=12/1=12 rows and 1 column.
12 elements with reshape(1,-1)
corresponds to an array with 1 row and x
=12/1=12 columns.
I could handle it using a groovy method in build.gradle
to create all source folders for java, resources and test. Then I set it to run before gradle eclipse
task.
eclipseClasspath.doFirst {
initSourceFolders()
}
def initSourceFolders() {
sourceSets*.java.srcDirs*.each { it.mkdirs() }
sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}
Now we can setup a new gradle Java EE project to eclipse with only one command. I put this example at GitHub
jQuery has an AjaxSetup()
function that allows you to register global ajax handlers such as beforeSend
and complete
for all ajax calls as well as allow you to access the xhr
object to do the progress that you are looking for
find . -type f |
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" |
xargs -p -n 2 mv
eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"
explanation:
1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"
2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)
example output:
foo_factory.py foo_service.py
bar_factory.py bar_service.py
3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.
The cunningly-named urlencode() and urldecode().
However, you shouldn't need to use urldecode()
on variables that appear in $_POST
and $_GET
.
Use SQL Server's date styles to pre-format your date values.
SELECT
CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero -- Date Style 101 = mm/dd/yyyy
,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero -- Date Style 103 = dd/mm/yyyy
Only solution that works was create a new conda env with the name you want (you will, unfortunately, delete the old one to keep the name). Then create a new env with a new python version and re-run your install.sh
script with the conda/pip installs (or the yaml file or whatever you use to keep your requirements):
conda remove --name original_name --all
conda create --name original_name python=3.8
sh install.sh # or whatever you usually do to install dependencies
doing conda install python=3.8
doesn't work for me. Also, why do you want 3.6? Move forward with the word ;)
If you want to update the conda version of your previous env what you can also do is the following (more complicated than it should be because you cannot rename envs in conda):
conda create --name temporary_env_name --clone original_env_name
conda deactivate
conda remove --name original_env_name --all # or its alias: `conda env remove --name original_env_name`
conda create --name original_env_name python=3.8 --clone temporary_env_name
Each row has an ID. All you have to do is to send this ID to the function setSelected()
, store it (in $scope.idSelectedVote
for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass
, if needed):
$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
$scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
...
</ul>
In windows serven and 8 and later in this location can find IE Cache
C:\Users\Username\AppData\Local\Microsoft\Windows\INetCache
A more definite way to target a td is table tr td { }
I found another reason PSEXEC (and other PS tools) fail - If something (...say, a virus or trojan) hides the Windows folder and/or its files, then PSEXEC will fail with an "Access is Denied" error, PSLIST will give the error "Processor performance object not found on " and you'll be left in the dark as to the reason.
You can RDP in; You can access the admin$ share; You can view the drive contents remotely, etc. etc., but there's no indication that file(s) or folder(s) being hidden is the reason.
I'll be posting this information on several pages that i was perusing yesterday while trying to determine the cause of this odd problem, so you might see this elsewhere verbatim - just thought I'd put the word out before anyone else pulled their hair out by the roots trying to understand why the performance counter has anything to do with PSEXEC running.
If you are using numpy, you have the argsort() function available:
>>> import numpy
>>> numpy.argsort(myList)
array([0, 1, 2, 4, 3])
http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
This returns the arguments that would sort the array or list.
I created my own little lazy Math-Object for degree (MathD), hope it helps:
//helper
/**
* converts degree to radians
* @param degree
* @returns {number}
*/
var toRadians = function (degree) {
return degree * (Math.PI / 180);
};
/**
* Converts radian to degree
* @param radians
* @returns {number}
*/
var toDegree = function (radians) {
return radians * (180 / Math.PI);
}
/**
* Rounds a number mathematical correct to the number of decimals
* @param number
* @param decimals (optional, default: 5)
* @returns {number}
*/
var roundNumber = function(number, decimals) {
decimals = decimals || 5;
return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
//the object
var MathD = {
sin: function(number){
return roundNumber(Math.sin(toRadians(number)));
},
cos: function(number){
return roundNumber(Math.cos(toRadians(number)));
},
tan: function(number){
return roundNumber(Math.tan(toRadians(number)));
},
asin: function(number){
return roundNumber(toDegree(Math.asin(number)));
},
acos: function(number){
return roundNumber(toDegree(Math.acos(number)));
},
atan: function(number){
return roundNumber(toDegree(Math.atan(number)));
}
};
I faced this error (errno 121) but it was caused by mysql-created intermediate tables that had been orphaned, preventing me from altering a table even though no such constraint name existed across any of my tables. At some point, my MySQL had crashed or failed to cleanup an intermediate table (table name starting with a #sql-) which ended up presenting me with an error such as: Can't create table '#sql-' (errno 121) when trying to run an ALTER TABLE with certain constraint names.
According to the docs at http://dev.mysql.com/doc/refman/5.7/en/innodb-troubleshooting-datadict.html , you can search for these orphan tables with:
SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE '%#sql%';
The version I was working with was 5.1, but the above command only works on versions >= 5.6 (manual is incorrect about it working for 5.5 or earlier, because INNODB_SYS_TABLES does not exist in such versions). I was able to find the orphaned temporary table (which did not match the one named in the message) by searching my mysql data directory in command line:
find . -iname '#*'
After discovering the filename, such as #sql-9ad_15.frm, I was able to drop that orphaned table in MySQL:
USE myschema;
DROP TABLE `#mysql50##sql-9ad_15`;
After doing so, I was then able to successfully run my ALTER TABLE.
For completeness, as per the MySQL documentation linked, "the #mysql50# prefix tells MySQL to ignore file name safe encoding introduced in MySQL 5.1."
Please make sure you have done below in your environment.rb file.
ENV['RAILS_ENV'] ||= 'production'
If you application runs in shared hosting environment or phushion passenger, you might need to need make changes in .httaccess (inside public folder) and set mode as production.
Great answers from a couple of years ago. Now Bitbucket has made it easier.
Tag the Commit you want to download (as mentioned in answer by Rudy Matela).
Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.
I've written a simple wrapper around git-checkout-index
that you can use like this:
git export ~/the/destination/dir
If the destination directory already exists, you'll need to add -f
or --force
.
Installation is simple; just drop the script somewhere in your PATH
, and make sure it's executable.
Update: Since I wrote this answer two years ago, we productized Mono to run on Android. The work included a few steps: porting Mono to Android, integrating it with Visual Studio, building plugins for MonoDevelop on Mac and Windows and exposing the Java Android APIs to .NET languages. This is now available at http://monodroid.net
Mono on Android is based on the Mono 2.10 runtime, and defaults to 4.0 profile with the C# 4.0 compiler and uses Mono's new SGen garbage collection engine, as well as our new distributed garbage collection system that performs GC across Java and Mono.
The links below reflect Mono on Android as of January of 2009, I have kept them for historical context
Mono now works on Android thanks to the work of Koushik Dutta and Marc Crichton.
You can see a video of it running here: http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html
And you can get the instructions to build Mono yourself here: http://www.koushikdutta.com/2009/01/building-mono-for-android.html
You can get a benchmark comparing Mono's JIT vs Dalvik's interpreter here: http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html
And of course, you can get a pre-configured image with Mono here (go to the bottom of the post for details on using that): http://www.koushikdutta.com/2009/01/building-mono-for-android.html
Addressing Steven's comment to Sam Dufel's answer
Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?
This should do the trick:
/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/
See this page for all the different variations of 'cats' that this matches.
You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.
For the OpenSuse comrades out there:
sudo zypper install python3-devel
Perl solution:
perl -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
If your input file is comma-separated:
perl -F, -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
output:
max columns: 5
rows: 2
-a
autosplits input line to @F
array
$#F
is the number of columns -1
-F,
field separator of , instead of whitespace
$.
is the line number (number of rows)
You can pass this
to each block. See here: http://jsfiddle.net/yR7TZ/1/
{{#each this}}
<div class="row"></div>
{{/each}}
Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.
def get_domain_suffixes():
import requests
res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
lst=set()
for line in res.text.split('\n'):
if not line.startswith('//'):
domains=line.split('.')
cand=domains[-1]
if cand:
lst.add('.'+cand)
return tuple(sorted(lst))
domain_suffixes=get_domain_suffixes()
def reminds_url(txt:str):
"""
>>> reminds_url('yandex.ru.com/somepath')
True
"""
ltext=txt.lower().split('/')[0]
return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)
Why not just set the left two columns to a fixed with in your own css and then make a new grid layout of the full 12 columns for the rest of the content?
<div class="row">
<div class="fixed-1">Left 1</div>
<div class="fixed-2">Left 2</div>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-11"></div>
</div>
</div>
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets
The reason why your full-width-div doesn't stretch 100% to your screen it's because of its parent "container" which occupies only about 80% of the screen.
If you want to make it stretch 100% to the screen either you make the "full-width-div" position fixed or use the "container-fluid" class instead of "container".
see Bootstrap 3 docs: http://getbootstrap.com/css/#grid
First way is
function function1()
{
var variable1=12;
function2(variable1);
}
function function2(val)
{
var variableOfFunction1 = val;
// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }
Second way is
var globalVariable;
function function1()
{
globalVariable=12;
function2();
}
function function2()
{
var local = globalVariable;
}
If you change the ManagementObjectSearcher to the following:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%""");
So the "GetUSBDevices() looks like this"
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
Your results will be limited to USB devices (as opposed to all types on your system)
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
when using 'git bash',
1) I execute the command:
docker exec -it 726fe4999627 /bin/bash
I have the error:
the input device is not a TTY. If you are using mintty, try prefixing the command with 'winpty'
2) then, I execute the command:
winpty docker exec -it 726fe4999627 /bin/bash
I have another error:
OCI runtime exec failed: exec failed: container_linux.go:344: starting container process caused "exec: \"D:/Git/usr/bin/
bash.exe\": stat D:/Git/usr/bin/bash.exe: no such file or directory": unknown
3) third, I execute the:
winpty docker exec -it 726fe4999627 bash
it worked.
when I using 'powershell', all worked well.
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content
You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.
EDIT: Adding the actual code:
Solution:
HTML snippet:
<a href="#" id="showAll" title="Show Tags">Show All Tags</a>
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
<li>Tag 1</li>
<li>Tag 2</li>
<li>Tag 3</li>
<li>Tag 4</li>
<li>Tag 5</li>
</ul>
Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
$(function() {
$('#showAll').click(function(){ //Adds click event listener
$('#tags').toggle('slow'); // Toggles visibility. Use the 'slow' parameter to add a nice effect.
});
});
You can test directly from this link: http://jsfiddle.net/vssJr/5/
Additional Comments on JQuery:
Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.
JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.
Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.
If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.
This might be what you're looking for:
// ... rest of code
// copy your state.data to a new array and sort it by itemM in ascending order
// and then map
const myData = [].concat(this.state.data)
.sort((a, b) => a.itemM > b.itemM ? 1 : -1)
.map((item, i) =>
<div key={i}> {item.matchID} {item.timeM}{item.description}</div>
);
// render your data here...
The method sort
will mutate the original array . Hence I create a new array using the concat
method. The sorting on the field itemM
should work on sortable entities like string and numbers.
To remove spaces... please use LTRIM
/RTRIM
LTRIM(String)
RTRIM(String)
The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.
SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers
Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi
The answer's here, I think.
It's better if you do git rm <fileName>
, though.
Use
substring_index(`column`,',',1) ==> first value
substring_index(substring_index(`column`,',',-2),',',1)=> second value
substring_index(substring_index(`column`,',',-1),',',1)=> third value
in your where clause.
SELECT * FROM `table`
WHERE
substring_index(`column`,',',1)<0
AND
substring_index(`column`,',',1)>5
The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.
scatter
, plot
, add_patch
)### imports
import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np
# https://stackoverflow.com/a/47166787/7128154
# https://matplotlib.org/3.3.3/api/collections_api.html#matplotlib.collections.PathCollection
# https://matplotlib.org/3.3.3/api/path_api.html#matplotlib.path.Path
# https://stackoverflow.com/questions/15876011/add-information-to-matplotlib-navigation-toolbar-status-bar
# https://stackoverflow.com/questions/36730261/matplotlib-path-contains-point
# https://stackoverflow.com/a/36335048/7128154
class StatusbarHoverManager:
"""
Manage hover information for mpl.axes.Axes object based on appearing
artists.
Attributes
----------
ax : mpl.axes.Axes
subplot to show status information
artists : list of mpl.artist.Artist
elements on the subplot, which react to mouse over
labels : list (list of strings) or strings
each element on the top level corresponds to an artist.
if the artist has items
(i.e. second return value of contains() has key 'ind'),
the element has to be of type list.
otherwise the element if of type string
cid : to reconnect motion_notify_event
"""
def __init__(self, ax):
assert isinstance(ax, mpl.axes.Axes)
def hover(event):
if event.inaxes != ax:
return
info = 'x={:.2f}, y={:.2f}'.format(event.xdata, event.ydata)
ax.format_coord = lambda x, y: info
cid = ax.figure.canvas.mpl_connect("motion_notify_event", hover)
self.ax = ax
self.cid = cid
self.artists = []
self.labels = []
def add_artist_labels(self, artist, label):
if isinstance(artist, list):
assert len(artist) == 1
artist = artist[0]
self.artists += [artist]
self.labels += [label]
def hover(event):
if event.inaxes != self.ax:
return
info = 'x={:.2f}, y={:.2f}'.format(event.xdata, event.ydata)
for aa, artist in enumerate(self.artists):
cont, dct = artist.contains(event)
if not cont:
continue
inds = dct.get('ind')
if inds is not None: # artist contains items
for ii in inds:
lbl = self.labels[aa][ii]
info += '; artist [{:d}, {:d}]: {:}'.format(
aa, ii, lbl)
else:
lbl = self.labels[aa]
info += '; artist [{:d}]: {:}'.format(aa, lbl)
self.ax.format_coord = lambda x, y: info
self.ax.figure.canvas.mpl_disconnect(self.cid)
self.cid = self.ax.figure.canvas.mpl_connect(
"motion_notify_event", hover)
def demo_StatusbarHoverManager():
fig, ax = plt.subplots()
shm = StatusbarHoverManager(ax)
poly = mpl.patches.Polygon(
[[0,0], [3, 5], [5, 4], [6,1]], closed=True, color='green', zorder=0)
artist = ax.add_patch(poly)
shm.add_artist_labels(artist, 'polygon')
artist = ax.scatter([2.5, 1, 2, 3], [6, 1, 1, 7], c='blue', s=10**2)
lbls = ['point ' + str(ii) for ii in range(4)]
shm.add_artist_labels(artist, lbls)
artist = ax.plot(
[0, 0, 1, 5, 3], [0, 1, 1, 0, 2], marker='o', color='red')
lbls = ['segment ' + str(ii) for ii in range(5)]
shm.add_artist_labels(artist, lbls)
plt.show()
# --- main
if __name__== "__main__":
demo_StatusbarHoverManager()
Personally I use the method of calling unregisterReceiver and swallowing the exception if it's thrown. I agree this is ugly but the best method currently provided.
I've raised a feature request to get a boolean method to check if a receiver is registered added to the Android API. Please support it here if you want to see it added: https://code.google.com/p/android/issues/detail?id=73718
As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.
You need to go to the GitHub page for your forked repository, and click on the “Settings” button.
Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.
From there, select placeholder (where placeholder is the dummy name for your new default branch).
Confirm that you want to change your default branch.
Now you can do (from the command line):
git push origin :master
Or, since 2012, you can delete that same branch directly on GitHub:
That was announced in Sept. 2013, a year after I initially wrote that answer.
For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.
Note: for BitBucket, Tum reports in the comments:
About the same for Bitbucket
Repo -> Settings -> Repository details -> Main branch
this works:
CSS:
.show_hide {
display:none;
}
.plus:after {
content:" +";
}
.minus:after {
content:" -";
}
jQuery:
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").addClass("plus").show();
$('.show_hide').toggle(
function(){
$(".slidingDiv").slideDown();
$(this).addClass("minus");
$(this).removeClass("plus");
},
function(){
$(".slidingDiv").slideUp();
$(this).addClass("plus");
$(this).removeClass("minus");
}
);
});
HTML:
<a href="#" class="show_hide">Show/hide</a>
<div class="slidingDiv" style="display: block;">
Check out the updated jQuery plugin for doing this: <a href="http://papermashup.com/jquery-show-hide-plugin/" class="show_hide" target="_blank" style="display: inline;">jQuery Show / Hide Plugin</a>
</div>
in the CSS, instead of content:" +";
You can put an background-image
(with background-position:right center;
and background-repeat:no-repeat
and maybe making the .show_hide
displayed as block and give him a width, so that the bg-image is not overlayed by the link-text itself).
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
At first glance one really wants to use New-PSDrive
supplying it credentials.
> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user
New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.
The documentation states that you can provide a PSCredential
object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.
Therefore you can either use net use
or the WScript.Network
object, calling the MapNetworkDrive
function:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")
Apparently with newer versions of PowerShell, the New-PSDrive
cmdlet works to map network shares with credentials!
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
In support of the answer provided by @Eddie Chen (here) I had to add http_proxy setting to following file as well:
C:\Windows\system32\config\systemprofile\AppData\Roaming\NuGet\NuGet.Config
<add key="http_proxy" value="http://your_proxy_url:8080" />
There's a good answer here:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
In Scala and Spark 2+, try this (assuming your column name is "s"):
df.select('s).as[String].collect
You can do something like this to read 10 bytes:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
remember read() doesn't add '\0'
to terminate to make it string (just gives raw buffer).
To read 1 byte at a time:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
and don't forget to #include <unistd.h>
, STDIN_FILENO
defined as macro in this file.
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
So instead STDIN_FILENO
you can use 0.
Edit:
In Linux System you can find this using following command:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
Notice the comment /* Standard input. */
In my case my RecyclerView
have a padding top like this
<android.support.v7.widget.RecyclerView
...
android:paddingTop="100dp"
android:clipToPadding="false"
/>
Then for scroll a item to top, I need to
recyclerViewLinearLayoutManager.scrollToPositionWithOffset(position, -yourRecyclerView.getPaddingTop());
I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.
If you are looking for a brand new pull from another branch like from local to master you can follow this.
git commit -m "Initial Commit"
git add .
git pull --rebase git_url
git push origin master
If I understood your question, here is the solution :
$.ajaxSetup({ cache: true});
and for specific calls
$.ajax({
url: ...,
type: "GET",
cache: false,
...
});
If you want opposite (cache for specific calls) you can set false at the beginning and true for specific calls.
I wanted to remotely watch a yum upgrade process that had been run locally, so while there were probably more efficient ways to do this, here's what I did:
watch cat /dev/vcsa1
Obviously you'd want to use vcsa2, vcsa3, etc., depending on which terminal was being used.
So long as my terminal window was of the same width as the terminal that the command was being run on, I could see a snapshot of their current output every two seconds. The other commands recommended elsewhere did not work particularly well for my situation, but that one did the trick.
Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools
"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types
How it works:
To set up Local Overrides:
UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides
A previous answer is mostly correct, but it will also match the empty string. The following would solve this.
^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$
All credits to @Martijn Pieters in the comments:
You can use the function last_insert_rowid()
:
The
last_insert_rowid()
function returns theROWID
of the last row insert from the database connection which invoked the function. Thelast_insert_rowid()
SQL function is a wrapper around thesqlite3_last_insert_rowid()
C/C++ interface function.
For completeness here is a floating-point implementation in bog-standard C.
double next_power_of_two(double value) {
int exp;
if(frexp(value, &exp) == 0.5) {
// Omit this case to round precise powers of two up to the *next* power
return value;
}
return ldexp(1.0, exp);
}
Yeah, disassemble is not the best command to use here. The command you want is "x/i" (examine as instructions):
(gdb) x/i 0xdeadbeef
This worked for me
In Controlle
ViewBag.AAA = default_Value ;
In View
@Html.EditorFor(model => model.AAA, new { htmlAttributes = new { @Value = ViewBag.AAA } }
if you are using SQL 2012 you should try
SELECT ID,
AccountID,
Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT,
FROM tCariH
if available, better order by date column.
Post both multiple text inputs plus multiple files via Ajax in one Ajax request
HTML
<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">
Jquery Code
$(document).on('click','#btnSendData',function (event) {
event.preventDefault();
var form = $('#myform')[0];
var formData = new FormData(form);
// Set header if need any otherwise remove setup part
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
url: "{{route('sendFormWithImage')}}",// your request url
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log(data);
},
error: function () {
}
});
});
A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)
#c1, #c2 {
width: 33%;
}
#c3 {
width: auto;
}
I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.
Casting because it works also with leading 0 like 00345
@Directive({
selector: '[appOnlyDigits]'
})
export class AppOnlyDigitsDirective {
@HostListener('input', ['$event'])
onKeyDown(ev: KeyboardEvent) {
const input = ev.target as HTMLInputElement;
input.value = String(input.value.replace(/\D+/g, ''));
}
}
Adding the following two lines at the top of my .py script worked for me (first line was necessary):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
TRUNCATE TABLE table;
is the SQL command. In PHP, you'd use:
mysql_query('TRUNCATE TABLE table;');
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
I could not resolve this with CSS. It seems like Boostrap is getting the last say even though I have by site.css after bootstrap. In any event, this worked for me.
$(document).ready(function () {
var elements = document.getElementsByClassName("form-control");
Array.from(elements).forEach(function () {
this.addEventListener("click", cbChange, false);
})
});
function cbChange(event) {
var ele = event.target;
var obj = document.getElementById(ele.id);
obj.style.borderColor = "lightgrey";
}
Later I found this to work in the css. Obviously with form-controls only
.form-control.focus, .form-control:focus {
border-color: gainsboro;
}
Here are before and after shots from Chrome Developer tool. Notice the difference in border color between focus on and focus off. On a side note, this does not work for buttons. With buttons. With buttons you have to change outline property to none.
Put the table in the second image on Sheet2, columns D to F.
In Sheet1, cell D2 use the formula
=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
copy across and down.
Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
In Python 3, map
returns an iterable object of type map
, and not a subscriptible list, which would allow you to write map[i]
. To force a list result, write
payIntList = list(map(int,payList))
However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)
just set empty string
<input type="text" id="textId" value="A new value">
document.getElementById('textId').value = '';
Apparently with Laravel 5.2, the closure in DB::listen
only receives a single parameter.
So, if you want to use DB::listen
in Laravel 5.2, you should do something like:
DB::listen(
function ($sql) {
// $sql is an object with the properties:
// sql: The query
// bindings: the sql query variables
// time: The execution time for the query
// connectionName: The name of the connection
// To save the executed queries to file:
// Process the sql and the bindings:
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->bindings);
// Save the query to file
$logFile = fopen(
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
'a+'
);
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
fclose($logFile);
}
);
It may be "better" to not use attach
at all. On the plus side, you can save some typing if you use attach
. Let's say your dataset is called mydata
and you have variables called v1
, v2
, and v3
. If you don't attach mydata
, then you will type mean(mydata$v1)
to get the mean of v1
. If you do attach mydata
, then you will type mean(v1)
to get the mean of v1
. But, if you don't detach the mydata
dataset (every time), you'll get the message about the objects being masked going forward.
detach
every time.Don't use attach
. Instead, include the dataset name every time you refer to a variable. The form is mydata$v1
(name of data set, dollar sign, name of variable).
As for me, I used solution 1 a lot in the past, but I've moved to solution 2. It's a bit more typing in the beginning, but if you are going to use the code multiple times, it just seems cleaner.
In my case, the program was running fine, but after one day, I just ran into this problem without doing anything...
The solution was to manually add 'Main' as the Entry Point (before editing, the area was empty):
If you leave any of the fields for ApplicationUser OR IdentityUser null the update will come back as successful but wont save the data in the database.
Example solution:
ApplicationUser model = UserManager.FindById(User.Identity.GetUserId())
Add the newly updated fields:
model.Email = AppUserViewModel.Email;
model.FName = AppUserViewModel.FName;
model.LName = AppUserViewModel.LName;
model.DOB = AppUserViewModel.DOB;
model.Gender = AppUserViewModel.Gender;
Call UpdateAsync
IdentityResult result = await UserManager.UpdateAsync(model);
I have tested this and it works.
You were almost right, there's just need one little fix to be made:
var a = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(1310522400000)
.ToLocalTime();
What exactly are you looking for when you mean multiline strings.
Are you looking for something like:
var str = "Some \
String \
Here";
Which would print as "Some String Here"?
If so, keep in mind that the above is valid Javascript, but this isn't:
var str = "Some \
String \
Here";
What's the difference? A space after the \
. Have fun debugging that.
The String#replaceAll()
interprets the argument as a regular expression. The \
is an escape character in both String
and regex
. You need to double-escape it for regex:
string.replaceAll("\\\\", "\\\\\\\\");
But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace()
should suffice:
string.replace("\\", "\\\\");
Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript()
instead to cover more characters.
Open up your DevTools and press F1 to access the settings. Look for the console section and check the checkbox for "Log XMLHttpRequests".
Now all of your ajax and other similar requests will be logged in the console.
I prefer this method because it usually allows me to see everything that I'm looking for in the console without having to go to the network tab.
window.location.href
is what you need. But also if you are using react router you might find useful checking out useLocation and useHistory hooks.
Both create an object with a pathname attribute you can read and are useful for a bunch of other stuff. Here's a youtube video explaining react router hooks
Both will give you what you need (without the domain name):
import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname
const history = useHistory()
history.location.pathname
If you have already pushed the wrong name to remote, do the following:
Switch to the local branch you want to rename
git checkout <old_name>
Rename the local branch
git branch -m <new_name>
Push the <new_name>
local branch and reset the upstream branch
git push origin -u <new_name>
Delete the <old_name>
remote branch
git push origin --delete <old_name>
This was based on this article.
in iis manager click directory to protect.
choose authorization rules.
add deny anonymous users rule.
add allow all users rule.
go back to: "in iis manager click directory to protect" click authentication disable all except basic authentication.
the directory is now protected. only people with user accounts can access the folder over the web.
set the overflow
property of a containing div
to scroll
.
With a list comprehension:
a = [x - 13 for x in a]
You want to grab the value of the first option in the select element.
$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
Add this to your section:
<script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; } </script>
And change your iframe to this:
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
It is posted Here
It does however use javascript, but it is simple and easy to use code that will fix your problem.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
Making Node.js code sync is essential in few aspects such as database. But actual advantage of Node.js lies in async code. As it is single thread non-blocking.
we can sync it using important functionality Fiber() Use await() and defer () we call all methods using await(). then replace the callback functions with defer().
Normal Async code.This uses CallBack functions.
function add (var a, var b, function(err,res){
console.log(res);
});
function sub (var res2, var b, function(err,res1){
console.log(res);
});
function div (var res2, var b, function(err,res3){
console.log(res3);
});
Sync the above code using Fiber(), await() and defer()
fiber(function(){
var obj1 = await(function add(var a, var b,defer()));
var obj2 = await(function sub(var obj1, var b, defer()));
var obj3 = await(function sub(var obj2, var b, defer()));
});
I hope this will help. Thank You
I personally prefer the simpler syntax of the ~ operator.
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;
Worth reading through Difference between LIKE and ~ in Postgres to understand the difference. `
Github has a great boilerplate .gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Rope
.ropeproject
# Django stuff:
*.log
*.pot
# Sphinx documentation
docs/_build/
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
This should work for everyone, any screen resolutions:
.modal-body {
max-height: calc(100vh - 143px);
overflow-y: auto; }
First, count your modal header and footer height, in my case I have H4
heading so I have them on 141px
, already counted default modal margin in 20px(top+bottom)
.
So that subtract 141px
is the max-height
for my modal height, for the better result there are both border top and bottom by 1px
, for this, 143px
will work perfectly.
In some case of styling you may like to use overflow-y: auto;
instead of overflow-y: scroll;
, try it.
Try it, and you get the best result in both computer or mobile devices.
If you have a heading larger than H4
, recount it see how much px
you would like to subtract.
If you don't know what I am telling, just change the number of 143px
, see what is the best result for your case.
Last, I'd suggest have it an inline CSS.
On macOs I manage to fix this by adding:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
to ~/.zsh_profile file.
and than type to your terminal
source $HOME/.zsh_profile
The issue was caused by using iTerm2 shell so it's required to edit its own config instead of default $HOME/.bash_profile as described in the official documentation https://reactnative.dev/docs/environment-setup
HTTP Servers tend to reject old browsers and systems.
The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection
or the system property "http.agent".
Often this question is asked in the context of Ron de Bruin's RangeToHTML
function, which creates an HTML PublishObject
from an Excel.Range
, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody
. In doing so, this removes the default signature (the RangeToHTML
function has a helper function GetBoiler
which attempts to insert the default signature).
Unfortunately, the poorly-documented Application.CommandBars
method is not available via Outlook:
wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
It will raise a runtime 6158:
But we can still leverage the Word.Document
which is accessible via the MailItem.GetInspector
method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).
Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed
With OutMail
.To = "[email protected]"
.BCC = ""
.Subject = "Subject"
.Display
Dim wdDoc As Object '## Word.Document
Dim wdRange As Object '## Word.Range
Set wdDoc = OutMail.GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
'Copy the range in-place
rng.Copy
wdRange.Paste
End With
Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:
Copy-pasted from here: Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating a new date):
var dt = new Date(); dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment(); var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();
Simply add icon in button element here is the example
<button class="social-signup facebook">
<i class="fa fa-facebook-official"></i>
Sign up with Facebook</button>
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
I wanted a function to create a comma-delimited list of question marks for JDBC purposes, and found this post. So, I decided to take two variants and see which one performed better. After 1 million iterations, the garden-variety StringBuilder took 2 seconds (fun1), and the cryptic supposedly more optimal version (fun2) took 30 seconds. What's the point of being cryptic again?
private static String fun1(int size) {
StringBuilder sb = new StringBuilder(size * 2);
for (int i = 0; i < size; i++) {
sb.append(",?");
}
return sb.substring(1);
}
private static String fun2(int size) {
return new String(new char[size]).replaceAll("\0", ",?").substring(1);
}
Well unless I misunderstand you can just use the onChange
attribute:
<input type="text" onChange="return bar()">
Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.
The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :
function getMax(dateArray, filler) {
filler= filler?filler:"";
if (!dateArray.length) {
return filler;
}
var max = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (max && d.valueOf()>max.valueOf()) {
max = d;
} else if (!max) {
max = d;
}
}
});
return max;
};
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));
function getMin(dateArray, filler) {
filler = filler ? filler : "";
if (!dateArray.length) {
return filler;
}
var min = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (min && d.valueOf() < min.valueOf()) {
min = d;
} else if (!min) {
min = d;
}
}
});
return min;
}
console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));
I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen
jQuery.fn.ownText = function () {
return $(this).contents().filter(function () {
return this.nodeType === Node.TEXT_NODE;
}).text();
};
I'm guessing that you want something like
SELECT tab1.a, tab2.b, tab3.c, tab4.d
FROM table1 tab1
JOIN table2 tab2 ON (tab1.fg = tab2.fg)
LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
tab3.dd = tab5.dd)
First of all
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
set-file-data="fileToUpload = value;" _x000D_
type="file" id="my_file" />
_x000D_
1.2 create own directive,
.directive("fileModel",function() {_x000D_
return {_x000D_
restrict: 'EA',_x000D_
scope: {_x000D_
setFileData: "&"_x000D_
},_x000D_
link: function(scope, ele, attrs) {_x000D_
ele.on('change', function() {_x000D_
scope.$apply(function() {_x000D_
var val = ele[0].files[0];_x000D_
scope.setFileData({ value: val });_x000D_
});_x000D_
});_x000D_
}_x000D_
}_x000D_
})
_x000D_
$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';
Then create separate function in controller to handle form submit call. like for e.g below code:
In service function handle "responseType" param purposely so that server should not throw "byteerror".
transformRequest, to modify request format with attached identity.
withCredentials : false, for HTTP authentication information.
in controller:_x000D_
_x000D_
// code this accordingly, so that your file object _x000D_
// will be picked up in service call below._x000D_
fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
.service('fileUpload', ['$http', 'ajaxService',_x000D_
function($http, ajaxService) {_x000D_
_x000D_
this.uploadFileToUrl = function(data) {_x000D_
var data = {}; //file object _x000D_
_x000D_
var fd = new FormData();_x000D_
fd.append('file', data.file);_x000D_
_x000D_
$http.post("endpoint server path to whom sending file", fd, {_x000D_
withCredentials: false,_x000D_
headers: {_x000D_
'Content-Type': undefined_x000D_
},_x000D_
transformRequest: angular.identity,_x000D_
params: {_x000D_
fd_x000D_
},_x000D_
responseType: "arraybuffer"_x000D_
})_x000D_
.then(function(response) {_x000D_
var data = response.data;_x000D_
var status = response.status;_x000D_
console.log(data);_x000D_
_x000D_
if (status == 200 || status == 202) //do whatever in success_x000D_
else // handle error in else if needed _x000D_
})_x000D_
.catch(function(error) {_x000D_
console.log(error.status);_x000D_
_x000D_
// handle else calls_x000D_
});_x000D_
}_x000D_
}_x000D_
}])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
I just set chrome as my default browser and jupyter launches in Chrome now.
However, we have also the following approach, but it did not work for me:
"CONDA version 4.7.5 and jupyter 6.0.0. - Windows 10"
1) Open Anaconda and launch your environment in terminal
2) Create config file and open file in notepad
3) Modify line of NotebookApp with chrome and save modification
4) Launch Jupyter
:( ... but it still launches in Mozilla.
var name = "nameGorge";
name.match(/[A-Z].*/)[0]
What you want to do is use Page.RegisterStartupScript(key, script) :
See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx
What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)
EDIT: This is what you call trigger happy. Feel free to down it. :)
This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.
document.querySelector('#fileInput').addEventListener('change', function () {_x000D_
_x000D_
var reader = new FileReader();_x000D_
var selectedFile = this.files[0];_x000D_
_x000D_
reader.onload = function () {_x000D_
var comma = this.result.indexOf(',');_x000D_
var base64 = this.result.substr(comma + 1);_x000D_
console.log(base64);_x000D_
}_x000D_
reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.
var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);
var firstPart = text.Substring(0,match.Groups[1].Index);
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;
getID3 supports video formats. See: http://getid3.sourceforge.net/
Edit: So, in code format, that'd be like:
include_once('pathto/getid3.php');
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");
Note: You must include the getID3 classes before this will work! See the above link.
Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See: http://ffmpeg-php.sourceforge.net/
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".
Further from UML standard:
composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).
So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)
Precise semantics of shared aggregation varies by application area and modeler.
I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.
Add classpath com.google.gms:google-services:3.0.0
dependencies at project level build.gradle
Refer the sample block from project level build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
Here is a great reference for HTML Ascii codes:
http://www.ascii.cl/htmlcodes.htm
The code you are looking for is: '
You can use the following list as quick reference:
/ = Root directory
. = This location
.. = Up a directory
./ = Current directory
../ = Parent of current directory
../../ = Two directories backwards
Useful article: https://css-tricks.com/quick-reminder-about-file-paths/
You can do it programmatically by reading the java
system properties
@Test
public void javaVersion() {
System.out.println(System.getProperty("java.version"));
System.out.println(System.getProperty("java.runtime.version"));
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("java.vendor"));
System.out.println(System.getProperty("java.vendor.url"));
System.out.println(System.getProperty("java.class.path"));
}
This will output somthing like
1.7.0_17
1.7.0_17-b02
C:\workspaces\Oracle\jdk1.7\jre
Oracle Corporation
http://java.oracle.com/
C:\workspaces\Misc\Miscellaneous\bin; ...
The first line shows the version number. You can parse it an see whether it fits your minimun required java version or not. You can find a description for the naming convention here and more infos here.
If all sorts of updating commando's won't do it. Try deleting package-lock.json. And then run npm install. Did the trick for me after going through tons of update commando's.