I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
One way can be to circularly store the values in the buffer array. and calculate average this way.
int j = (int) (counter % size);
buffer[j] = mostrecentvalue;
avg = (avg * size - buffer[j - 1 == -1 ? size - 1 : j - 1] + buffer[j]) / size;
counter++;
// buffer[j - 1 == -1 ? size - 1 : j - 1] is the oldest value stored
The whole thing runs in a loop where most recent value is dynamic.
My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation.
template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y)
{
double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0);
double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0);
double mx = sum_x / x.size();
double my = sum_y / y.size();
double accum = 0.0;
for (auto i = 0; i < x.size(); i++)
{
accum += (x.at(i) - mx) * (y.at(i) - my);
}
return accum / (x.size() - 1);
}
A couple of things for ya:
The loading would be "better" like this:
with file('morsecodes.txt', 'rt') as f:
for line in f:
line = line.strip()
if len(line) > 0:
# do your stuff to parse the file
That way you don't need to close, and you don't need to manually load each line, etc., etc.
for letter in userInput:
if ValidateLetter(letter): # you need to define this
code = GetMorseCode(letter) # from my other answer
# do whatever you want
You can use as follows
public ActionResult NewWindow()
{
return Content("<script>window.open('{url}','_blank')</script>");
}
It is always best practice to do something like this.
var $request;
if ($request != null){
$request.abort();
$request = null;
}
$request = $.ajax({
type : "POST", //TODO: Must be changed to POST
url : "yourfile.php",
data : "data"
}).done(function(msg) {
alert(msg);
});
But it is much better if you check an if statement to check whether the ajax request is null or not.
This is not about the difference between Window.ContentRendered
and Window.Loaded
but about what how the Window.Loaded
event can be used:
I use it to avoid splash screens in all applications which need a long time to come up.
// initializing my main window
public MyAppMainWindow()
{
InitializeComponent();
// Set the event
this.ContentRendered += MyAppMainWindow_ContentRendered;
}
private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
{
// ... comes up quick when the controls are loaded and rendered
// unset the event
this.ContentRendered -= MyAppMainWindow_ContentRendered;
// ... make the time comsuming init stuff here
}
You can do it easily with ouzo goodies
$result = array_map(Functions::extract()->id, $arr);
or with Arrays (from ouzo goodies)
$result = Arrays::map($arr, Functions::extract()->id);
Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
See also functional programming with ouzo (I cannot post a link).
You Can try This To Run Command Then cmd
Exits
Process.Start("cmd", "/c YourCode")
You Can try This To Run The Command And Let cmd
Wait For More Commands
Process.Start("cmd", "/k YourCode")
we can create nested cte.please see the below cte in example
;with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)
select * from cte_data,cte_data1
Below is a implementation of Graph Data Structure in C++ as Adjacency List.
I have used STL vector for representation of vertices and STL pair for denoting edge and destination vertex.
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
struct vertex {
typedef pair<int, vertex*> ve;
vector<ve> adj; //cost of edge, destination vertex
string name;
vertex(string s) : name(s) {}
};
class graph
{
public:
typedef map<string, vertex *> vmap;
vmap work;
void addvertex(const string&);
void addedge(const string& from, const string& to, double cost);
};
void graph::addvertex(const string &name)
{
vmap::iterator itr = work.find(name);
if (itr == work.end())
{
vertex *v;
v = new vertex(name);
work[name] = v;
return;
}
cout << "\nVertex already exists!";
}
void graph::addedge(const string& from, const string& to, double cost)
{
vertex *f = (work.find(from)->second);
vertex *t = (work.find(to)->second);
pair<int, vertex *> edge = make_pair(cost, t);
f->adj.push_back(edge);
}
I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.
Just in case anyone stumbles on this one, I've got another solution, not relying on dir reading or extending the Class class...
ActiveRecord::Base.send :subclasses
This will return an array of classes. So you can then do
ActiveRecord::Base.send(:subclasses).map(&:name)
See if your settings are correct also:
Window -> Preferences -> Java -> Editor -> content assist. See if the "completion inserts" is checked off along with anything else there you want to help auto complete.
I'm using simple alias to create pull request,
alias pr='open -n -a "Google Chrome" --args "https://github.com/user/repo/compare/pre-master...nawarkhede:$(git_current_branch)\?expand\=1"'
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
There's a difference between the header and body of a HTTP response. PUT should never return a body, but must return a response code in the header. Just choose 200 if it was successful, and 4xx if not. There is no such thing as a null return code. Why do you want to do this?
Just a small addition to Nick's answer (which works great !) :
If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:
jQuery.validator.addMethod("lettersonly", function(value, element)
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");
Apart from all said by others.. In an older project that I used to work for, a lot of communication between entities(independent applications) was using integers which represented a small set. It was useful to declare the set as enum
with static methods to get enum
object from value
and viceversa. The code looked cleaner, switch case usability and easier writing to logs.
enum ProtocolType {
TCP_IP (1, "Transmission Control Protocol"),
IP (2, "Internet Protocol"),
UDP (3, "User Datagram Protocol");
public int code;
public String name;
private ProtocolType(int code, String name) {
this.code = code;
this.name = name;
}
public static ProtocolType fromInt(int code) {
switch(code) {
case 1:
return TCP_IP;
case 2:
return IP;
case 3:
return UDP;
}
// we had some exception handling for this
// as the contract for these was between 2 independent applications
// liable to change between versions (mostly adding new stuff)
// but keeping it simple here.
return null;
}
}
Create enum
object from received values (e.g. 1,2) using ProtocolType.fromInt(2)
Write to logs using myEnumObj.name
Hope this helps.
I've successfully mount /home/<user-name>
folder of my host to the /mnt
folder of the existing (not running) container. You can do it in the following way:
Open configuration file corresponding to the stopped container, which can be found at /var/lib/docker/containers/99d...1fb/config.v2.json
(may be config.json
for older versions of docker).
Find MountPoints
section, which was empty in my case: "MountPoints":{}
. Next replace the contents with something like this (you can copy proper contents from another container with proper settings):
"MountPoints":{"/mnt":{"Source":"/home/<user-name>","Destination":"/mnt","RW":true,"Name":"","Driver":"","Type":"bind","Propagation":"rprivate","Spec":{"Type":"bind","Source":"/home/<user-name>","Target":"/mnt"},"SkipMountpointCreation":false}}
or the same (formatted):
"MountPoints": {
"/mnt": {
"Source": "/home/<user-name>",
"Destination": "/mnt",
"RW": true,
"Name": "",
"Driver": "",
"Type": "bind",
"Propagation": "rprivate",
"Spec": {
"Type": "bind",
"Source": "/home/<user-name>",
"Target": "/mnt"
},
"SkipMountpointCreation": false
}
}
service docker restart
This works for me with Ubuntu 18.04.1 and Docker 18.09.0
Please remove the servlet jar from web project,as any how, the application/web server already had.
I have one function that lpad with x decimals: CREATE FUNCTION [dbo].[LPAD_DEC] ( -- Add the parameters for the function here @pad nvarchar(MAX), @string nvarchar(MAX), @length int, @dec int ) RETURNS nvarchar(max) AS BEGIN -- Declare the return variable here DECLARE @resp nvarchar(max)
IF LEN(@string)=@length
BEGIN
IF CHARINDEX('.',@string)>0
BEGIN
SELECT @resp = CASE SIGN(@string)
WHEN -1 THEN
-- Nros negativos grandes con decimales
concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
-- Nros positivos grandes con decimales
concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))
END
END
ELSE
BEGIN
SELECT @resp = CASE SIGN(@string)
WHEN -1 THEN
--Nros negativo grande sin decimales
concat('-',SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
-- Nros positivos grandes con decimales
concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))
END
END
END
ELSE
IF CHARINDEX('.',@string)>0
BEGIN
SELECT @resp =CASE SIGN(@string)
WHEN -1 THEN
-- Nros negativos con decimales
concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
--Ntos positivos con decimales
concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
END
END
ELSE
BEGIN
SELECT @resp = CASE SIGN(@string)
WHEN -1 THEN
-- Nros Negativos sin decimales
concat('-',SUBSTRING(replicate(@pad,@length-3),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
-- Nros Positivos sin decimales
concat(SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
END
END
RETURN @resp
END
Just add ExecJS and the Ruby Racer in your gem file and run bundle install
after.
gem 'execjs'
gem 'therubyracer'
Everything should be fine after.
input{
text-align:center;
}
is all you need.
Working example in FF6. This method doesn't seem to be cross-browser compatible.
Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".
Do you have a specific database selected like so:
USE database_name
Except for that I can't think of any reason for this error.
This is for those who want to overwrite the column cells quickly (without cutting and copying). This is the same as double-clicking the cell box but unlike double-clicking, it still works after the first try.
BONUS:
The shortcut for going to the bottom-most content (to double-check the copy) is Ctrl+⇓. To go back up you can use Ctrl+⇑ but if your top rows are frozen you'll also have to press Enter a few times.
Just a small adittion to @johnharris85's great answer,
when you are running a docker compose file, a "default
" network is created
so you can just add it to the other compose file as an external network:
# front/docker-compose.yml
version: '2'
services:
front_service:
...
...
# api/docker-compose.yml
version: '2'
services:
api_service:
...
networks:
- front_default
networks:
front_default:
external: true
For me this approach was more suited because I did not own the first docker-compose file and wanted to communicate with it.
Add this at the start of main
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");
//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
"Although I can't isolate SQL as the source of the problem anymore, I still feel like it is."
Fire up SQL Profiler and take a look. Take the resulting queries and check their execution plans to make sure that index is being used.
This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.
The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).
You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.
mockStatic(Internalutils.class);
So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.
@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {
@Mock
private InternalService.Order order;
private InternalService internalService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
internalService = new InternalService();
}
@Test
public void processOrder() throws Exception {
Mockito.when(order.isSuccessful()).thenReturn(true);
PowerMockito.mockStatic(InternalService.InternalUtils.class);
internalService.processOrder(order);
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
}
}
These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
This is code of my class, sendEmail api twice.
public class InternalService {
public void processOrder(Order order) {
if (order.isSuccessful()) {
InternalUtils.sendEmail("", new String[1], "", "");
InternalUtils.sendEmail("", new String[1], "", "");
}
}
public static class InternalUtils{
public static void sendEmail(String from, String[] to, String msg, String body){
}
}
public class Order{
public boolean isSuccessful(){
return true;
}
}
}
As it is calling twice you just need to change the verify(times(2))... that's all.
It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.
Please see this page for more details.
I store encoded HTML in the database.
Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:
<div class='content'>
@Model.Content
</div>
PowerShell currently doesn't didn't have a native Inline If (or ternary If) but you could consider to use the custom cmdlet:
IIf <condition> <condition-is-true> <condition-is-false>
I had to map FAKE/REAL to 0/1 but couldn't find proper answer.
Please find below how to map column name 'type' which has values FAKE/REAL to 0/1
(Note: similar can be applied to any column name and values)
df.loc[df['type'] == 'FAKE', 'type'] = 0
df.loc[df['type'] == 'REAL', 'type'] = 1
Let df be the dataframe you have with col names myDays and temp. If you want to rename "myDays" to "Date",
library(plyr)
rename(df,c("myDays" = "Date"))
or with pipe, you can
dfNew <- df %>%
plyr::rename(c("myDays" = "Date"))
To reorder the rows of a DataFrame just use a list as follows.
df = df[['Mid', 'Net', 'Upper', 'Lower', 'Zsore']]
This makes it very obvious what was done when reading the code later. Also use:
df.columns
Out[1]: Index(['Net', 'Upper', 'Lower', 'Mid', 'Zsore'], dtype='object')
Then cut and paste to reorder.
For a DataFrame with many columns, store the list of columns in a variable and pop the desired column to the front of the list. Here is an example:
cols = [str(col_name) for col_name in range(1001)]
data = np.random.rand(10,1001)
df = pd.DataFrame(data=data, columns=cols)
mv_col = cols.pop(cols.index('77'))
df = df[[mv_col] + cols]
Now df.columns
has.
Index(['77', '0', '1', '2', '3', '4', '5', '6', '7', '8',
...
'991', '992', '993', '994', '995', '996', '997', '998', '999', '1000'],
dtype='object', length=1001)
This should work:
Process.Start(@"<directory goes here>")
Or if you'd like a method to run programs/open files and/or folders:
private void StartProcess(string path)
{
ProcessStartInfo StartInformation = new ProcessStartInfo();
StartInformation.FileName = path;
Process process = Process.Start(StartInformation);
process.EnableRaisingEvents = true;
}
And then call the method and in the parenthesis put either the directory of the file and/or folder there or the name of the application. Hope this helped!
Important Edit: This answer is outdated. Since writing it, the Visibility API (mdn, example, spec) has been introduced. It is the better way to solve this problem.
var focused = true;
window.onfocus = function() {
focused = true;
};
window.onblur = function() {
focused = false;
};
AFAIK, focus
and blur
are all supported on...everything. (see http://www.quirksmode.org/dom/events/index.html )
I encounter an situation that is rare, but this may help other friends in similar situation. I have to work on an older system with gcc 4.4.7. I have to compile code with c++11 or above support, so I build the latest version of gcc 5.3.0. When building my code and linking to the dependencies if the dependency is build with older compiler, then I got 'undefined reference to' error even though I clearly defined the linking path with -L/path/to/lib -llibname. Some packages such as boost and projects build with cmake usually has a tendency to use the older compiler, and they usually cause such problems. You have to go a long way to make sure they use the newer compiler.
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
You can simply do
node --version
or short form would also do
node -v
If above commands does not work, you have done something wrong in installation, reinstall the node.js and try.
If your array is populated through an SQL Query consider reversing the result in MySQL, ie :
SELECT * FROM model_input order by creation_date desc
We can specify how we have to join the string. Instead of '-', we can use ' '
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
Define "necessary".
It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type
header to text/html
if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:
<b><i>test</i></b>
a Content-Type: text/html
would output:
test
whereas Content-Type: text/plain
would output:
<b><i>test</i></b>
TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.
run npm i moment react-moment --save
you can use this in your component,
import Moment from 'react-moment';
const date = new Date();
<Moment format='MMMM Do YYYY, h:mm:ss a'>{date}</Moment>
An IntPtr
is a value type that is primarily used to hold memory addresses or handles. A pointer is a memory address. A pointer can be typed (e.g. int*
) or untyped (e.g. void*
). A Windows handle is a value that is usually the same size (or smaller) than a memory address and represents a system resource (like a file or window).
Try this:
for(var i = 0; i < data.length; i++){
console.log(data[i].com)
}
In my condition when I got an exception " Unable to start embedded Tomcat servlet container",
I opened the debug mode of spring boot by adding debug=true
in the application.properties,
and then rerun the code ,and it told me that java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String
Thus, we know that probably I'm using a servlet API of lower version, and it conflicts with spring boot version.
I went to my pom.xml, and found one of my dependencies is using servlet2.5, and I excluded it.
Now it works. Hope it helps.
You can use the .blur()
method. See http://api.jquery.com/blur/
This is how I got rid of it:
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
I am creating xxx that maps all the relationships between a main table (like Products table) and reference tables (like ProductType or ProductDescriptionByLanguage). This will create a view that will allow me retrieve a product and all it's details translated from its foreign keys to its description. Then I can use an ORM to create objects to easily build grids, combo boxes, etc.
I did a small mistake that should be kept in mind. If you are using your keystore then give your alias name, not androiddebugkey...
I solved my problem. Now if Facebook is there installed in my device, then still my app is getting data on the Facebook login integration. Just only care about your hash key.
Please see below.
C:\Program Files\Java\jdk1.6.0_45\bin>keytool -exportcert -alias here your alias name -keystore "G:\yourkeystorename.keystore" |"G:\ssl\bin\openssl" sha1 -binary | "G:\ssl\bin\openssl" base64
Then press Enter - it will ask you for the password and then enter your keystore password, not Android.
Cool.
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
Here I post a simple way of solution
CREATE FUNCTION [dbo].[split](
@delimited NVARCHAR(MAX),
@delimiter NVARCHAR(100)
) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
DECLARE @xml XML
SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'
INSERT INTO @t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM @xml.nodes('/t') as records(r)
RETURN
END
Execute the function like this
select * from dbo.split('Hello John Smith',' ')
For any Git newbies like me, here are some steps you could follow to download a remote repository, and then switch to the branch that you want to view. They probably abuse Git in some way, but it did the job for me! :-)
Clone the repository you want to download the code for (in this example I've picked the LRResty project on Github):
$ git clone https://github.com/lukeredpath/LRResty.git
$ cd LRResty
Check what branch you are using at this point (it should be the master branch):
$ git branch
* master
Check out the branch you want, in my case it is called 'arcified':
$ git checkout -b arcified origin/arcified
Branch arcified set up to track remote branch arcified from origin.
Switched to a new branch 'arcified'
Confirm you are now using the branch you wanted:
$ git branch
* arcified
master
If you want to update the code again later, run git pull
:
$ git pull
Already up-to-date.
Before messing with Nginx config, try to disable ChromePHP first.
chromephp:
type: chromephp
level: info
ChromePHP pack the debug info json-encoded in the X-ChromePhp-Data header, which is too big for the default config of nginx with fastcgi.
As of Python 3.2 2.7, there is now argparse for processing command line arguments.
You can also use the info provided by a php exception, it's an elegant solution:
function GetCallingMethodName(){ $e = new Exception(); $trace = $e->getTrace(); //position 0 would be the line that called this function so we ignore it $last_call = $trace[1]; print_r($last_call); } function firstCall($a, $b){ theCall($a, $b); } function theCall($a, $b){ GetCallingMethodName(); } firstCall('lucia', 'php');
And you get this... (voilà!)
Array ( [file] => /home/lufigueroa/Desktop/test.php [line] => 12 [function] => theCall [args] => Array ( [0] => lucia [1] => php ) )
Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/
enter code here
ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/
while (scr.hasNext()){
list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */
All the above answers are generating an issue which is that col[0].column is returning number while worksheet.column_dimensions[column] accepts only character such as 'A', 'B', 'C' in place of column. I've modified @Virako's code and it is working fine now.
import re
import openpyxl
..
for col in _ws.columns:
max_lenght = 0
print(col[0])
col_name = re.findall('\w\d', str(col[0]))
col_name = col_name[0]
col_name = re.findall('\w', str(col_name))[0]
print(col_name)
for cell in col:
try:
if len(str(cell.value)) > max_lenght:
max_lenght = len(cell.value)
except:
pass
adjusted_width = (max_lenght+2)
_ws.column_dimensions[col_name].width = adjusted_width
I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.
png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
x = rnorm(500, mean = rep(1:5, 100)),
y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))
ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
Here it is the first figure:
and the second figure:
As we can see the colors do not stay fixed, for example E switches from magenta to blu.
As suggested by malcook in his comment and by hadley in his comment the code which uses limits
works properly:
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +
geom_point() +
scale_colour_discrete(drop=TRUE,
limits = levels(dataset$fCategory))
gives the following figure, which is correct:
This is the output from sessionInfo()
:
R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] methods stats graphics grDevices utils datasets base
other attached packages:
[1] ggplot2_0.9.3.1
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 dichromat_2.0-0 digest_0.6.4 grid_3.0.2
[5] gtable_0.1.2 labeling_0.2 MASS_7.3-29 munsell_0.4.2
[9] plyr_1.8 proto_0.3-10 RColorBrewer_1.0-5 reshape2_1.2.2
[13] scales_0.2.3 stringr_0.6.2
As of Rails 5
, it is recommended to put the lib folder under app directory or instead create other meaningful name spaces for the folder as services
, presenters
, features
etc and put it under app directory for auto loading by rails.
Please check this GitHub Discussion Link as well.
Create a custom Windows Service.
I had some mission-critical tasks set up as scheduled console apps and found them difficult to maintain. I created a Windows Service with a 'heartbeat' that would check a schedule in my DB every couple of minutes. It's worked out really well.
Having said that, I still use scheduled console apps for most of my non-critical maintenance tasks. If it ain't broke, don't fix it.
Found this to work well cross browser and mobile back_button_override.js .
(Added a timer for safari 5.0)
// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("back", null, null);
window.onpopstate = function () {
history.pushState('back', null, null);
if(count == 1){window.location = 'your url';}
};
}
}
setTimeout(function(){count = 1;},200);
If you validate , option 1 comes up as an error in html 5, so option 2 is correct.
var numbers = [1, 1, 2, 3, 4, 4];_x000D_
_x000D_
function unique(dupArray) {_x000D_
return dupArray.reduce(function(previous, num) {_x000D_
_x000D_
if (previous.find(function(item) {_x000D_
return item == num;_x000D_
})) {_x000D_
return previous;_x000D_
} else {_x000D_
previous.push(num);_x000D_
return previous;_x000D_
}_x000D_
}, [])_x000D_
}_x000D_
_x000D_
var check = unique(numbers);_x000D_
console.log(check);
_x000D_
The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".
<meta http-equiv="refresh" content="15" >
This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.
Let us know if it worked/solved your problem!?
-Brad
In Mac OS X (tried with Android Studio), do the following in Terminal
cd /android/adt-bundle-mac-x86_64/sdk/tools
sudo ./android sdk
This launches SDK manager as admin. Now update/install the packages from SDK manager and it'll work.
That's HTML, but yes, you can bang pretty much any selectors you like together.
#x.y { }
(And the HTML is fine too)
You could use CONCAT, and the numeric argument of it is converted to its equivalent binary string form.
select t2.*
from t1 join t2
on t2.url=CONCAT('site.com/path/%', t1.id, '%/more') where t1.id > 9000
You can use array.nbytes
for numpy arrays, for example:
>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192
In Simple word- package.json of your project has not property of repository you must have to add it,
and you have to add repository in your package.json like below
and Let me explain according to your scenario
you must have to add repository field something like below
"repository" : {
"type" : "git",
"url" : "http://github.com/npm/express.git"
}
Works in most shells
TESTSTRINGONE="MOTEST"
NEWTESTSTRING=${TESTSTRINGONE%"${TESTSTRINGONE#?????}"}
echo ${NEWTESTSTRING}
# MOTES
Try to give max-content
for parent's height.
.parent{
height: max-content;
}
For IIS 8 There is a extra step to do other than changing the customErrors=Off to show the error content.
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors existingResponse="PassThrough" errorMode="Detailed"/>
</system.webServer>
Raul answered the question in this link Turn off IIS8 custom errors by Raul
Okay, found it!
I'm using timezone-js. this is the code:
var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");
console.debug(dt); //return formatted date-time in asia/jakarta
here you go get_the_category( $post->ID );
will return the array of categories of that post you need to loop through the array
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}
Command line usage:
for /f %f in ('dir /b c:\') do echo %f
Batch file usage:
for /f %%f in ('dir /b c:\') do echo %%f
Update: if the directory contains files with space in the names, you need to change the delimiter the for /f
command is using. for example, you can use the pipe char.
for /f "delims=|" %%f in ('dir /b c:\') do echo %%f
Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq
option on the for
:
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f
And if you need to use output redirection or command piping, use the escape char (^
):
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
You can do something like this:
((long) (num * 1E308 * 1E308) >> 63) == 0 ? "+ve" : "-ve"
The main idea here is that we cast to a long and check the value of the most significant bit. As a double/float between -1 and 0 will round to zero when cast to a long, we multiply by large doubles so that a negative float/double will be less than -1. Two multiplications are required because of the existence of subnormals (it doesn't really need to be that big though).
Razor is just a templating engine.
You should create a regular class.
If you want to make a method inside of a Razor page, put them in an @functions
block.
For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string
to either int
or Guid
, if you're still getting
EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.
you probably just forgot to specify the new key type on IdentityDbContext
:
public class AppIdentityDbContext : IdentityDbContext<
AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
public AppIdentityDbContext()
: base("MY_CONNECTION_STRING")
{
}
......
}
If you just have
public class AppIdentityDbContext : IdentityDbContext
{
......
}
or even
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
......
}
you will get that 'no key defined' error when you are trying to add migrations or update the database.
As a tangential note, one case where the ability to have multiple .gitignore
files is very useful is if you want an extra directory in your working copy that you never intend to commit. Just put a 1-byte .gitignore
(containing just a single asterisk) in that directory and it will never show up in git status
etc.
Split the text into lines, and draw each separately:
function fillTextMultiLine(ctx, text, x, y) {
var lineHeight = ctx.measureText("M").width * 1.2;
var lines = text.split("\n");
for (var i = 0; i < lines.length; ++i) {
ctx.fillText(lines[i], x, y);
y += lineHeight;
}
}
The pass
command is what you are looking for. Use pass
for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.
For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:
if num2 != num5:
make_some_changes()
This will be the same as this:
if num2 == num5:
pass
else:
make_some_changes()
That way you won't even have to use pass
and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.
You can read more about the pass
statement in the documentation:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
if condition:
pass
try:
make_some_changes()
except Exception:
pass # do nothing
class Foo():
pass # an empty class definition
def bar():
pass # an empty function definition
What I did was: Added/Updated the following code:
framework: 'jasmine',
jasmineNodeOpts:
{
// Jasmine default timeout
defaultTimeoutInterval: 60000,
expectationResultHandler(passed, assertion)
{
// do something
},
}
If you use the relative version on http://www.foo.com/abc your browser will look at http://www.foo.com/abc/kitten.png for the image and would get 404 - Not found.
where is the file created?
In the application's current working directory. You can use os.getcwd
to check it, and os.chdir
to change it.
Opening file in the root directory probably fails due to lack of privileges.
Add
session_start();
at the beginning of your page before any HTML
You will have something like :
<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
The one exception worth noting is that while you can't delete apps, the folks over at Google Play Developer Support are able to on their end if the app is both unpublished and has 0 lifetime installs. So if your app has 0 lifetime installs, you might be in luck.
First you will need unpublish the app and wait 24 hours (to allow global stats to update and ensure that no last-minute installs happened). Assuming no last-minute installs happen over those 24 hours, you can contact Google Play Developer Support and check to see if they can delete it.
Please note that their requirement for 0 installs is a hard requirement. No exceptions can be made (not even if you installed the app yourself for testing purposes).
Directory.GetFiles("C:\\", "*.*", SearchOption.AllDirectories)
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
This is how to use chai to deeply test associative arrays.
I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)
I did it by defining the variable as an object (not array) prior to my function call:
var myAssocArray = {}; // not []
var expectedAssocArray = {}; // not []
expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';
// legacy function which returns associate array reference
myFunction(myAssocArray);
assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');
Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore
to the getter.
Which you've tried:
Add @JsonIgnore on the getter method only
Do this, and also add a specific @JsonProperty
annotation for your JSON "password" field name to the setter method for the password on your object.
More recent versions of Jackson have added READ_ONLY
and WRITE_ONLY
annotation arguments for JsonProperty
. So you could also do something like:
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
Docs can be found here.
One more example for 2 dimension String array:
public void arrayExam() {
List<String[]> A = new ArrayList<String[]>();
A.add(new String[] {"Jack","good"});
A.add(new String[] {"Mary","better"});
A.add(new String[] {"Kate","best"});
for (String[] row : A) {
Log.i(TAG,row[0] + "->" + row[1]);
}
}
Output:
17467 08-02 19:24:40.518 8456 8456 I MyExam : Jack->good
17468 08-02 19:24:40.518 8456 8456 I MyExam : Mary->better
17469 08-02 19:24:40.518 8456 8456 I MyExam : Kate->best
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Update that may help Ubuntu users if they still want to use the ? and ? instead of another set of keys.
I just installed a fresh version of VSCode on Ubuntu 18.04 LTS and I had duplicate commands for Add Cursor Above
and Add Cursor Below
I just removed the bindings that used Ctrl and added my own with the following
Copy Line Up
Ctrl + Shift + ?
Copy Line Down
Ctrl + Shift + ?
While Sam Saffron did great work on it, he still didn't provide recursive common table expression code for this problem. And for us who working with SQL Server 2008 R2 and not Denali, it's still fastest way to get running total, it's about 10 times faster than cursor on my work computer for 100000 rows, and it's also inline query.
So, here it is (I'm supposing that there's an ord
column in the table and it's sequential number without gaps, for fast processing there also should be unique constraint on this number):
;with
CTE_RunningTotal
as
(
select T.ord, T.total, T.total as running_total
from #t as T
where T.ord = 0
union all
select T.ord, T.total, T.total + C.running_total as running_total
from CTE_RunningTotal as C
inner join #t as T on T.ord = C.ord + 1
)
select C.ord, C.total, C.running_total
from CTE_RunningTotal as C
option (maxrecursion 0)
-- CPU 140, Reads 110014, Duration 132
update
I also was curious about this update with variable or quirky update. So usually it works ok, but how we can be sure that it works every time? well, here's a little trick (found it here - http://www.sqlservercentral.com/Forums/Topic802558-203-21.aspx#bm981258) - you just check current and previous ord
and use 1/0
assignment in case they are different from what you expecting:
declare @total int, @ord int
select @total = 0, @ord = -1
update #t set
@total = @total + total,
@ord = case when ord <> @ord + 1 then 1/0 else ord end,
------------------------
running_total = @total
select * from #t
-- CPU 0, Reads 58, Duration 139
From what I've seen if you have proper clustered index/primary key on your table (in our case it would be index by ord_id
) update will proceed in a linear way all the time (never encountered divide by zero). That said, it's up to you to decide if you want to use it in production code :)
update 2 I'm linking this answer, cause it includes some useful info about unreliability of the quirky update - nvarchar concatenation / index / nvarchar(max) inexplicable behavior.
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
One of the best examples of Hadoop-like MapReduce implementation.
Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
For the other answers to work "from a server" first Turn On Access for less secure apps in the gmail account.
Looks like recently google changed it's security policy. The top rated answer no longer works, until you change your account settings as described here: https://support.google.com/accounts/answer/6010255?hl=en-GB
As of March 2016, google changed the setting location again!
I also encuntered the same in S4. I've tested the app in Galaxy Grand , HTC , Sony Experia but got only in s4. You can ignore it as its not related to your app.
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
in Swift 4.2 and Xcode 10
Initially my text field is like this.
After adding padding in left side my text field is...
//Code for left padding
textFieldName.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: textFieldName.frame.height))
textFieldName.leftViewMode = .always
Like this we can create right side also.(textFieldName.rightViewMode = .always)
If you want SharedInstance type code(Write once use every ware) see the below code.
//This is my shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//This is my padding function.
func textFieldLeftPadding(textFieldName: UITextField) {
// Create a padding view
textFieldName.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 3, height: textFieldName.frame.height))
textFieldName.leftViewMode = .always//For left side padding
textFieldName.rightViewMode = .always//For right side padding
}
private override init() {
}
}
Now call this function like this.
//This single line is enough
SharedClass.sharedInstance.textFieldLeftPadding(textFieldName:yourTF)
Try this, in your parent frame set up you IFRAMEs like this:
<iframe id="frame1" src="inner.html#frame1"></iframe>
<iframe id="frame2" src="inner.html#frame2"></iframe>
<iframe id="frame3" src="inner.html#frame3"></iframe>
Note that the id of each frame is passed as an anchor in the src.
then in your inner html you can access the id of the frame it is loaded in via location.hash:
<button onclick="alert('I am frame: ' + location.hash.substr(1))">Who Am I?</button>
then you can access parent.document.getElementById() to access the iframe tag from inside the iframe
no_of_lines = 5
lines = ""
for i in xrange(5):
lines+=input()+"\n"
a=raw_input("if u want to continue (Y/n)")
""
if(a=='y'):
continue
else:
break
print lines
Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml
Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.
Happy Android developments guys!!!
Wow! when you use src
then src
of searchPic
must be used also.
document["pic1"].src = searchPic.src
looks better
You could use an extension method for fun. Typically I don't recommend attaching extension methods to such a general purpose class like string, but like I said this is fun. I borrowed @Luke's answer since there is no point in re-inventing the wheel.
[Test]
public void Should_remove_first_occurrance_of_string() {
var source = "ProjectName\\Iteration\\Release1\\Iteration1";
Assert.That(
source.RemoveFirst("\\Iteration"),
Is.EqualTo("ProjectName\\Release1\\Iteration1"));
}
public static class StringExtensions {
public static string RemoveFirst(this string source, string remove) {
int index = source.IndexOf(remove);
return (index < 0)
? source
: source.Remove(index, remove.Length);
}
}
Here is the NodeJS REST api for two PDF render scripts. https://github.com/pumppi/pdf2images
Scripts are: pdf2svg and Imagemagicks convert
This code will return your Date object formatted with the browser timezone.
Date.prototype.timezone = function () {
this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
return this;
}
Edit:
To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.
function setTimeZone(date) {
date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
return date;
}
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
"Select your text, right click, then choose
Style Token
and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."
It should be default, but it might be hidden.
"It might be that something happened to your
contextMenu.xml
so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\
) if thecontextMenu.xml
is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at thecontextmenu.xml
itself - because you're allowed to change it to your own needs."
See this for more information
Here's how to determine a local user:
public bool IsLocalUser()
{
return windowsIdentity.AuthenticationType == "NTLM";
}
You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.
Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:
Why the NTLM Plug-in is Needed
NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.
Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.
By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.
How the Plug-in Works
The Verifier plug detects the following errors:
The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).
The target name in the call to InitializeSecurityContext is NULL.
The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.
The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).
The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.
NTLM Stops
5000 – Application Has Explicitly Selected NTLM Package
Severity – Error
The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.
How to Fix this Error
The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.
APIs(parameter) Used by Application Incorrect Value Correct Value ===================================== =============== ======================== AcquireCredentialsHandle (pszPackage) “NTLM” NEGOSSP_NAME “Negotiate”
Above two answers are correct but didn't work for me.
docker container ls
docker container ls -a
and after that it showed all the process previously exited and running.docker stop <container id>
or docker container stop <container id>
didn't work docker rm -f <container id>
and it worked.docker container ls -a
and this process wasn't present.You can use cut with a delimiter like this:
with space delim:
cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv
with tab delim:
cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv
I gave you the version of cut in which you can extract a list of intervals...
Hope it helps!
Use command-line option -v
or --invert-match
,
ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$
KISS : Keep it simple, stupid
Way A: Implement an own SortableBindingList class when like to use DataBinding and sorting.
Way B: Use a List<string> sorting works also but does not work with DataBinding.
Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.
void RemoveAll<T>(T item,List<T> list)
{
while(list.Contains(item)) list.Remove(item);
}
With predicate:
void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
while(list.Any(predicate)) list.Remove(list.First(predicate));
}
+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.
Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.
In your first example, list.Contains()
and Remove()
are both O(n), so a while()
loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).
Your second example is even worse: O(n3), because for every time you call Remove()
, you also call First(predicate)
, which is also O(n). Think about it: Any(predicate)
loops over the list looking for any element for which predicate()
returns true. Once it finds the first such element, it returns true. In the body of the while()
loop, you then call list.First(predicate)
which loops over the list a second time looking for the same element that had already been found by list.Any(predicate)
. Once First()
has found it, it returns that element which is passed to list.Remove()
, which loops over the list a third time to yet once again find that same element that was previously found by Any()
and First()
, in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.
Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate)
method, which is O(n) as long as your predicate is O(1). A for()
loop technique that passes over the list only once, calling list.RemoveAt()
for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for()
loop implementation is O(m*n) since each call to Remove()
is O(n). Since the for()
loop itself is O(n), and it calls Remove()
m times, the for()
loop's growth is O(n2) as m approaches n.
The normal procedure with Eclipse and Java EE webapplications is to install a servlet container (Tomcat, Jetty, etc) or application server (Glassfish (which is bundled in the "Sun Java EE" download), JBoss AS, WebSphere, Weblogic, etc) and integrate it in Eclipse using a (builtin) plugin in the Servers view.
During the creation wizard of a new Dynamic Web Project, you can then pick the integrated server from the list. If you happen to have an existing Dynamic Web Project without a server or want to change the associated one, then you need to modify it in the Targeted Rutimes section of the project's properties.
Either way, Eclipse will automatically place the necessary server-specific libraries in the project's classpath (buildpath).
You should absolutely in no way extract and copy server-specific libraries into /WEB-INF/lib
or even worse the JRE/lib
yourself, to "fix" the compilation errors in Eclipse. It would make your webapplication tied to a specific server and thus completely unportable.
Go to
window->Preference->server->runtime environment
then choose your tomcat server. If the error is still there, then
right click project->properties>Targeted Runtimes
then check the server
Someone has already made a benchmark: jQuery document.createElement equivalent?
$(document.createElement('div'))
is the big winner.
I know this is a super old post, but I figured this may still be helpful.
If you're comfortable with reading json format you could replace your var_dump with:
return json_encode($myvar);
I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.
Also, because the json_encoded data is a string it means you can write it to the error log easily
error_log(json_encode($myvar));
It probably isn't the best choice for every situation, but it's a choice!
Pretty redundant attribute, considering the "asp" tag is obviously an ASP element and should be enough to identify it as a server side accessible element.
Elsewhere however it used to elevate normal tags to be used in the code-behind.
listofIDs.Select(int.Parse).ToList()
Since I'm too low reputation to comment, I will post this as an answer since it saved me after hours of struggeling and it may help somebody else:
As most people state GC.Collect(); is NOT recommended to do this normally, except in edge cases. As an example of this running garbage collection was exactly the solution to my scenario.
My program runs a long running operation on a file in a thread and afterwards deletes the file from the main thread. However: when the file operation throws an exception .NET does NOT release the filelock until the garbage is actually collected, EVEN when the long running task is encapsulated in a using statement. Therefore the program has to force garbage collection before attempting to delete the file.
In code:
var returnvalue = 0;
using (var t = Task.Run(() => TheTask(args, returnvalue)))
{
//TheTask() opens a file and then throws an exception. The exception itself is handled within the task so it does return a result (the errorcode)
returnvalue = t.Result;
}
//Even though at this point the Thread is closed the file is not released untill garbage is collected
System.GC.Collect();
DeleteLockedFile();
Use:
subA.tick_params(labelsize=6)
The guide to getting fired: How to abuse function pointers in GCC on x86 machines by compiling your code by hand:
These string literals are bytes of 32-bit x86 machine code. 0xC3
is an x86 ret
instruction.
You wouldn't normally write these by hand, you'd write in assembly language and then use an assembler like nasm
to assemble it into a flat binary which you hexdump into a C string literal.
Returns the current value on the EAX register
int eax = ((int(*)())("\xc3 <- This returns the value of the EAX register"))();
Write a swap function
int a = 10, b = 20;
((void(*)(int*,int*))"\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3 <- This swaps the values of a and b")(&a,&b);
Write a for-loop counter to 1000, calling some function each time
((int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3")(&function); // calls function with 1->1000
You can even write a recursive function that counts to 100
const char* lol = "\x8b\x5c\x24\x4\x3d\xe8\x3\x0\x0\x7e\x2\x31\xc0\x83\xf8\x64\x7d\x6\x40\x53\xff\xd3\x5b\xc3\xc3 <- Recursively calls the function at address lol.";
i = ((int(*)())(lol))(lol);
Note that compilers place string literals in the .rodata
section (or .rdata
on Windows), which is linked as part of the text segment (along with code for functions).
The text segment has Read+Exec permission, so casting string literals to function pointers works without needing mprotect()
or VirtualProtect()
system calls like you'd need for dynamically allocated memory. (Or gcc -z execstack
links the program with stack + data segment + heap executable, as a quick hack.)
To disassemble these, you can compile this to put a label on the bytes, and use a disassembler.
// at global scope
const char swap[] = "\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3 <- This swaps the values of a and b";
Compiling with gcc -c -m32 foo.c
and disassembling with objdump -D -rwC -Mintel
, we can get the assembly, and find out that this code violates the ABI by clobbering EBX (a call-preserved register) and is generally inefficient.
00000000 <swap>:
0: 8b 44 24 04 mov eax,DWORD PTR [esp+0x4] # load int *a arg from the stack
4: 8b 5c 24 08 mov ebx,DWORD PTR [esp+0x8] # ebx = b
8: 8b 00 mov eax,DWORD PTR [eax] # dereference: eax = *a
a: 8b 1b mov ebx,DWORD PTR [ebx]
c: 31 c3 xor ebx,eax # pointless xor-swap
e: 31 d8 xor eax,ebx # instead of just storing with opposite registers
10: 31 c3 xor ebx,eax
12: 8b 4c 24 04 mov ecx,DWORD PTR [esp+0x4] # reload a from the stack
16: 89 01 mov DWORD PTR [ecx],eax # store to *a
18: 8b 4c 24 08 mov ecx,DWORD PTR [esp+0x8]
1c: 89 19 mov DWORD PTR [ecx],ebx
1e: c3 ret
not shown: the later bytes are ASCII text documentation
they're not executed by the CPU because the ret instruction sends execution back to the caller
This machine code will (probably) work in 32-bit code on Windows, Linux, OS X, and so on: the default calling conventions on all those OSes pass args on the stack instead of more efficiently in registers. But EBX is call-preserved in all the normal calling conventions, so using it as a scratch register without saving/restoring it can easily make the caller crash.
If I understand you correctly, you want to list to exclude duplicates on one column only, inner join to a sub-select
select u.* [whatever joined values]
from users u
inner join
(select name from users group by name having count(*)=1) uniquenames
on uniquenames.name = u.name
if you are using python3.7, then the best solution is using
datetime.isoformat()
and
datetime.fromisoformat()
; they work with both naive and
aware datetime
objects:
#!/usr/bin/env python3.7
from datetime import datetime
from datetime import timezone
from datetime import timedelta
import json
def default(obj):
if isinstance(obj, datetime):
return { '_isoformat': obj.isoformat() }
return super().default(obj)
def object_hook(obj):
_isoformat = obj.get('_isoformat')
if _isoformat is not None:
return datetime.fromisoformat(_isoformat)
return obj
if __name__ == '__main__':
#d = { 'now': datetime(2000, 1, 1) }
d = { 'now': datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=-8))) }
s = json.dumps(d, default=default)
print(s)
print(d == json.loads(s, object_hook=object_hook))
output:
{"now": {"_isoformat": "2000-01-01T00:00:00-08:00"}}
True
if you are using python3.6 or below, and you only care about the time value (not
the timezone), then you can use datetime.timestamp()
and
datetime.fromtimestamp()
instead;
if you are using python3.6 or below, and you do care about the timezone, then
you can get it via datetime.tzinfo
, but you have to serialize this field
by yourself; the easiest way to do this is to add another field _tzinfo
in the
serialized object;
finally, beware of precisions in all these examples;
While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, 'xyc"foo');return false;">Test</a>
The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..
example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.
It permanently comments out that code so the compiler will never compile it.
The coder can later change the #ifdef to have that code compile in the program if he wants to.
It's exactly like the code doesn't exist.
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
If you are planning to use JSONP
you can use getJSON
which made for that. jQuery has helper methods for JSONP
.
$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
console.log(result);
});
Read the below links
http://api.jquery.com/jQuery.getJSON/
Tools -> Options -> Show All Settings -> Text Editor -> All Languages -> Line Numbers
copy your file in linux Java directory
cp yourfile.jar /java/bin
open the directory
cd /java/bin
and execute your file
./java -jar yourfile.jar
or all in one try this command:
/java/bin/java -jar jarfilefolder/jarfile.jar
I would prefer using the most easiest method.
Right click on the Wamp icon and go to
Tools > Use a port other than 8080 >
Set a different port, lets say 8081 and that's it. Problem resolved.
You are most welcome.
You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.
For XLS file: HSSFWorkbook
& HSSFSheet
For XLSX file: XSSFSheet
& XSSFSheet
So in place of XSSFWorkbook
use HSSFWorkbook
and in place of XSSFSheet
use HSSFSheet
.
So your code should look like this after the changes are made:
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
This is one of the most annoying things about Maven. For me the following happens: If I add a dependency requesting more dependencies and more and more but have a slow connection, it seams to stop while downloading and timing out. While timing out all dependencies not yet fetched are marked with place holders in the .m2 cache and Maven will not (never) pick it up unless I remove the place holder entry from the cache (as other stated) by removing it.
So as far as I see it, Maven or more precise the Eclipse Maven plugin has a bug regarding this. Someone should report this.
I got this error because I tried to rename a sheet with too many characters
In Android
Android has a built in class for managing URIs.
Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()
I wrote this answer back in '09 when Android was relatively new, and there were many not well established areas in Android development. I have added a long addendum at the bottom of this post, addressing some criticism, and detailing a philosophical disagreement I have with the use of Singletons rather than subclassing Application. Read it at your own risk.
ORIGINAL ANSWER:
The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.
As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.
The way to do this is to create your own subclass of android.app.Application, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context
using the Context.getApplicationContext()
method (Activity
also provides a method getApplication()
which has the exact same effect). Following is an extremely simplified example, with caveats to follow:
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).
Something to note from the example above; suppose we had instead done something like:
class MyApp extends Application {
private String myState = /* complicated and slow initialization */;
public String getState(){
return myState;
}
}
Now this slow initialization (such as hitting disk, hitting network, anything blocking, etc) will be performed every time Application is instantiated! You may think, well, this is only once for the process and I'll have to pay the cost anyways, right? For instance, as Dianne Hackborn mentions below, it is entirely possible for your process to be instantiated -just- to handle a background broadcast event. If your broadcast processing has no need for this state you have potentially just done a whole series of complicated and slow operations for nothing. Lazy instantiation is the name of the game here. The following is a slightly more complicated way of using Application which makes more sense for anything but the simplest of uses:
class MyApp extends Application {
private MyStateManager myStateManager = new MyStateManager();
public MyStateManager getStateManager(){
return myStateManager ;
}
}
class MyStateManager {
MyStateManager() {
/* this should be fast */
}
String getState() {
/* if necessary, perform blocking calls here */
/* make sure to deal with any multithreading/synchronicity issues */
...
return state;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyStateManager stateManager = ((MyApp)getApplicationContext()).getStateManager();
String state = stateManager.getState();
...
}
}
While I prefer Application subclassing to using singletons here as the more elegant solution, I would rather developers use singletons if really necessary over not thinking at all through the performance and multithreading implications of associating state with the Application subclass.
NOTE 1: Also as anticafe commented, in order to correctly tie your Application override to your application a tag is necessary in the manifest file. Again, see the Android docs for more info. An example:
<application
android:name="my.application.MyApp"
android:icon="..."
android:label="...">
</application>
NOTE 2: user608578 asks below how this works with managing native object lifecycles. I am not up to speed on using native code with Android in the slightest, and I am not qualified to answer how that would interact with my solution. If someone does have an answer to this, I am willing to credit them and put the information in this post for maximum visibility.
ADDENDUM:
As some people have noted, this is not a solution for persistent state, something I perhaps should have emphasized more in the original answer. I.e. this is not meant to be a solution for saving user or other information that is meant to be persisted across application lifetimes. Thus, I consider most criticism below related to Applications being killed at any time, etc..., moot, as anything that ever needed to be persisted to disk should not be stored through an Application subclass. It is meant to be a solution for storing temporary, easily re-creatable application state (whether a user is logged in for example) and components which are single instance (application network manager for example) (NOT singleton!) in nature.
Dayerman has been kind enough to point out an interesting conversation with Reto Meier and Dianne Hackborn in which use of Application subclasses is discouraged in favor of Singleton patterns. Somatik also pointed out something of this nature earlier, although I didn't see it at the time. Because of Reto and Dianne's roles in maintaining the Android platform, I cannot in good faith recommend ignoring their advice. What they say, goes. I do wish to disagree with the opinions, expressed with regards to preferring Singleton over Application subclasses. In my disagreement I will be making use of concepts best explained in this StackExchange explanation of the Singleton design pattern, so that I do not have to define terms in this answer. I highly encourage skimming the link before continuing. Point by point:
Dianne states, "There is no reason to subclass from Application. It is no different than making a singleton..." This first claim is incorrect. There are two main reasons for this. 1) The Application class provides a better lifetime guarantee for an application developer; it is guaranteed to have the lifetime of the application. A singleton is not EXPLICITLY tied to the lifetime of the application (although it is effectively). This may be a non-issue for your average application developer, but I would argue this is exactly the type of contract the Android API should be offering, and it provides much more flexibility to the Android system as well, by minimizing the lifetime of associated data. 2) The Application class provides the application developer with a single instance holder for state, which is very different from a Singleton holder of state. For a list of the differences, see the Singleton explanation link above.
Dianne continues, "...just likely to be something you regret in the future as you find your Application object becoming this big tangled mess of what should be independent application logic." This is certainly not incorrect, but this is not a reason for choosing Singleton over Application subclass. None of Diane's arguments provide a reason that using a Singleton is better than an Application subclass, all she attempts to establish is that using a Singleton is no worse than an Application subclass, which I believe is false.
She continues, "And this leads more naturally to how you should be managing these things -- initializing them on demand." This ignores the fact that there is no reason you cannot initialize on demand using an Application subclass as well. Again there is no difference.
Dianne ends with "The framework itself has tons and tons of singletons for all the little shared data it maintains for the app, such as caches of loaded resources, pools of objects, etc. It works great." I am not arguing that using Singletons cannot work fine or are not a legitimate alternative. I am arguing that Singletons do not provide as strong a contract with the Android system as using an Application subclass, and further that using Singletons generally points to inflexible design, which is not easily modified, and leads to many problems down the road. IMHO, the strong contract the Android API offers to developer applications is one of the most appealing and pleasing aspects of programming with Android, and helped lead to early developer adoption which drove the Android platform to the success it has today. Suggesting using Singletons is implicitly moving away from a strong API contract, and in my opinion, weakens the Android framework.
Dianne has commented below as well, mentioning an additional downside to using Application subclasses, they may encourage or make it easier to write less performance code. This is very true, and I have edited this answer to emphasize the importance of considering perf here, and taking the correct approach if you're using Application subclassing. As Dianne states, it is important to remember that your Application class will be instantiated every time your process is loaded (could be multiple times at once if your application runs in multiple processes!) even if the process is only being loaded for a background broadcast event. It is therefore important to use the Application class more as a repository for pointers to shared components of your application rather than as a place to do any processing!
I leave you with the following list of downsides to Singletons, as stolen from the earlier StackExchange link:
and add my own:
MacPorts and Homebrew provide a coreutils package containing greadlink
(GNU readlink). Credit to Michael Kallweitt post in mackb.com.
brew install coreutils
greadlink -f file.txt
Create outlets from views that were created in StoryBoard.
@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var greenView: UIView!
Override the touchesBegan method. There are 2 options, everyone can determine which one is better for him.
Detect touch in special view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
if touch.view == self.redView {
tapOnredViewTapped()
} else if touch.view == self.orangeView {
orangeViewTapped()
} else if touch.view == self.greenView {
greenViewTapped()
} else {
return
}
}
}
Detect touch point on special view.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: view)
if redView.frame.contains(location) {
redViewTapped()
} else if orangeView.frame.contains(location) {
orangeViewTapped()
} else if greenView.frame.contains(location) {
greenViewTapped()
}
}
}
Lastly, you need to declare the functions that will be called, depending on which view the user clicked.
func redViewTapped() {
print("redViewTapped")
}
func orangeViewTapped() {
print("orangeViewTapped")
}
func greenViewTapped() {
print("greenViewTapped")
}
I have found that the VT char is used in pptx text boxes at the end of each line shown in the box in oder to adjust the text to the size of the box. It seems to be automatically generated by powerpoint (not introduced by the user) in order to move the text to the next line and fix the complete text block to the text box. In the example below, in the position of §:
"This is a text §
inside a text box"
I have a simple approach.
Step 1: Mount /var/run/docker.sock:/var/run/docker.sock (So you will be able to execute docker commands inside your container)
Step 2: Execute this below inside your container. The key part here is (--network host as this will execute from host context)
docker run -i --rm --network host -v /opt/test.sh:/test.sh alpine:3.7 sh /test.sh
test.sh should contain the some commands (ifconfig, netstat etc...) whatever you need. Now you will be able to get host context output.
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
In case MySQL Server is up but you are still getting the error:
For anyone who still have this issue, I followed awesome tutorial http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-9-mavericks/
However i still got #1045 error.
What really did the trick was to change localhost
to 127.0.0.1
at your config.inc.php
. Why was it failing if locahost points to 127.0.0.1? I don't know. But it worked.
===== EDIT =====
Long story short, it is because of permissions in mysql. It may be set to accept connections from 127.0.0.1 but not from localhost.
The actual answer for why this isn't responding is here: https://serverfault.com/a/297310
This page might interest you: http://msdn.microsoft.com/en-us/magazine/dd722812.aspx
You can generate the XML documentation file using either the command-line compiler or through the Visual Studio interface. If you are compiling with the command-line compiler, use options /doc or /doc+. That will generate an XML file by the same name and in the same path as the assembly. To specify a different file name, use /doc:file.
If you are using the Visual Studio interface, there's a setting that controls whether the XML documentation file is generated. To set it, double-click My Project in Solution Explorer to open the Project Designer. Navigate to the Compile tab. Find "Generate XML documentation file" at the bottom of the window, and make sure it is checked. By default this setting is on. It generates an XML file using the same name and path as the assembly.
When I had the same problem I fixed it by deleting the existing key.snk
in that project and adding a new key.
That's not exactly what I had in mind. What do you do if you have a generic type to only be known at runtime?
public MyDTO toObject() {
try {
var methodInfo = MethodBase.GetCurrentMethod();
if (methodInfo.DeclaringType != null) {
var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName;
Type type = Type.GetType(fullName);
if (type != null) {
var obj = JsonConvert.DeserializeObject(payload);
//var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload); // <--- type ?????
...
}
}
// Example for java.. Convert this to C#
return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader()));
} catch (Exception ex) {
throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex);
}
}
The problem is that the root's (the main layout you store the other elements) gravity is not set. If you change it to center the other elements' gravity must work just fine.
you can use following helper function:
function content(divSelector, value) {
document.querySelector(divSelector).innerHTML = value;
}
content('#content',"whatever");
Where #content
must be valid CSS selector
Here is working example.
Additionaly - today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever'); // jQuery
The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.
So the winners are pure js and firefox (3x faster than chrome!)
You can test it in your machine: https://jsperf.com/js-jquery-html-content-change
package main
import "fmt"
func main() {
var x float64 = 5.7
var y int = int(x)
fmt.Println(y) // outputs "5"
}
First you should decide what is your particular purpose. The official Python documentation on extending and embedding the Python interpreter was mentioned above, I can add a good overview of binary extensions. The use cases can be divided into 3 categories:
In order to give some broader perspective for other interested and since your initial question is a bit vague ("to a C or C++ library") I think this information might be interesting to you. On the link above you can read on disadvantages of using binary extensions and its alternatives.
Apart from the other answers suggested, if you want an accelerator module, you can try Numba. It works "by generating optimized machine code using the LLVM compiler infrastructure at import time, runtime, or statically (using the included pycc tool)".
As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.
After 9.2.x. IOS remove this tag check on its' browser.
You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html
You can try jquery-collision. Full disclosure: I just wrote this and released it. I didn't find a solution, so I wrote it myself.
It allows you to do:
var hit_list = $("#ball").collision("#someobject0");
which will return all the "#someobject0"'s that overlap with "#ball".
I had the same problem. This is my solution, I'm not sure that is the good practice, tell me if not:
state = {
value: this.props.value
};
componentDidUpdate(prevProps) {
if(prevProps.value !== this.props.value) {
this.setState({value: this.props.value});
}
}
UPD: Now you can do the same thing using React Hooks: (only if component is a function)
const [value, setValue] = useState(propName);
// This will launch only if propName value has chaged.
useEffect(() => { setValue(propName) }, [propName]);
Set up a device for development https://developer.android.com/studio/run/device.html#setting-up
Enable developer options and debugging https://developer.android.com/studio/debug/dev-options.html#enable
Optional
Here's how I do it in a bash script:
if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep
then
echo "The script is already running."
exit 1
fi
This allows me to use this snippet for any bash script. I needed to grep bash because when using with cron, it creates another process that executes it using /bin/sh.
For anyone else looking for help on this matter, or experiencing a FileNotFoundException or a FirstChanceException, check out my answer here:
In general you must be absolutely certain that you are meeting all of the requirements for making the reference - I know it's the obvious answer, but you're probably overlooking a relatively simple requirement.
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load()
method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType()
function to decide on which one to play).
You can then wait for either the loadedmetadata
or loadeddata
(depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
Why the fuss?
replace(haystack, haystack %in% needles, replacements)
Demo:
haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")
replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"
For Bootstrap 4:
Just use
<ul class="navbar-nav mx-auto">
mx-auto will do the job
The best way to do this is by running the command:
git diff --name-only --cached
When you check the manual you will likely find the following:
--name-only
Show only names of changed files.
And on the example part of the manual:
git diff --cached
Changes between the index and your current HEAD.
Combined together you get the changes between the index and your current HEAD
and Show only names of changed files.
Update: --staged
is also available as an alias for --cached
above in more recent git versions.
hit git init using terminal/cmd in your desired folder. It'll do the job.
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
If you're running Linux I would suggest two tools:
align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html
compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.
align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.
The classes for the OOXML file formats (such as XSSF for .xlsx) are in a different Jar file. You need to include the poi-ooxml jar in your project, along with the dependencies for it
You can get a list of all the components and their dependencies on the POI website here.
What you probably want to do is download the 3.11 binary package, grab the poi-ooxml
jar from it, and the dependencies in the ooxml-lib
directory. Import these into your project and you'll be sorted.
Alternately, if you use Maven, you can see here for the list of the artificats you'll want to depend on, but it'd want to be something like:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
The poi-ooxml maven dependency will pull in the main POI jar and the dependencies for you automatically. If you want to work with the non-spreadsheet formats, you'd also want to depend on the poi-scratchpad
artifact too, as detailed on the POI components page
I can attest to the fact that -webkit-transform: translate3d(0, 0, 0);
will mess with the new position: -webkit-sticky;
property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.
Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased
on the html element. I was testing this behavior in iOS7 and Android.
To Nihat's point (above): Evan You has advised against using _uid: "The vm _uid is reserved for internal use and it's important to keep it private (and not rely on it in user code) so that we keep the flexibility to change its behavior for potential future use cases. ... I'd suggest generating UIDs yourself [using a module, a global mixin, etc.]"
Using the suggested mixin in this GitHub issue to generate the UID seems like a better approach:
let uuid = 0;
export default {
beforeCreate() {
this.uuid = uuid.toString();
uuid += 1;
},
};
The +
operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d
is a non-zero number.
I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:
It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)
I'm using OS Catalina and used the solution of Babul Prabhakar. But when I closed the terminal, pod still was unable.
So I put the exports:
$ export GEM_HOME=$HOME/Software/ruby
$ export PATH=$PATH:$HOME/Software/ruby/bin
inside this file(put this command below inside the terminal):
nano ~/.bash_profile
Then save the file, close the terminal and open it up again and type:
pod --version
In Windows xp sp3 you can use sleep command
You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title
-match
is for regex matching ( the second argument is a regex )
One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.
OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.
<script>
function dostuff() {
if (document.getElementById('MyBox').style.height == "0px") {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;");
}
else {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;");
}
}
</script>
<div id="MyBox" style="height: 0px; width: 0px;">
</div>
<input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
I have been hasseling with that as other folks have.
I used the criteria;
=countif(matchingList,C2)=0
where matchingList is the list that i am using as a filter.
have a look at this
http://www.youtube.com/watch?v=x47VFMhRLnM&list=PL63A7644FE57C97F4&index=30
The trick i found is that normally you would have the column heading in the criteria matching the data column heading. this will not work for criteria that is a formula.
What I found was if I left the column heading blank for only the criteria that has the countif
formula in the advanced filter works. If I have the column heading i.e. the column heading for column C2 in my formula example then the filter return no output.
Hope this helps
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
A bit unrelated answer to OP but for people like me with a somewhat similar problem.
Use Case: Ubuntu (C, Clion, Auto-completion):
I had the same error,
CMake Error: Cannot determine link language for target "hello".
set_target_properties(hello PROPERTIES LINKER_LANGUAGE C)
help fixes that problem but the headers aren't included to the project and the autocompletion wont work.
This is what i had
cmake_minimum_required(VERSION 3.5)
project(hello)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES ./)
add_executable(hello ${SOURCE_FILES})
set_target_properties(hello PROPERTIES LINKER_LANGUAGE C)
No errors but not what i needed, i realized including a single file as source will get me autocompletion as well as it will set the linker to C
.
cmake_minimum_required(VERSION 3.5)
project(hello)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES ./1_helloworld.c)
add_executable(hello ${SOURCE_FILES})
Here is the content of the file MessageBoxManager.cs
#pragma warning disable 0618
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]
namespace System.Windows.Forms
{
public class MessageBoxManager
{
private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
private const int WH_CALLWNDPROCRET = 12;
private const int WM_DESTROY = 0x0002;
private const int WM_INITDIALOG = 0x0110;
private const int WM_TIMER = 0x0113;
private const int WM_USER = 0x400;
private const int DM_GETDEFID = WM_USER + 0;
private const int MBOK = 1;
private const int MBCancel = 2;
private const int MBAbort = 3;
private const int MBRetry = 4;
private const int MBIgnore = 5;
private const int MBYes = 6;
private const int MBNo = 7;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
private static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[DllImport("user32.dll")]
private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetDlgCtrlID(IntPtr hwndCtl);
[DllImport("user32.dll")]
private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
private static extern bool SetWindowText(IntPtr hWnd, string lpString);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
private static HookProc hookProc;
private static EnumChildProc enumProc;
[ThreadStatic]
private static IntPtr hHook;
[ThreadStatic]
private static int nButton;
/// <summary>
/// OK text
/// </summary>
public static string OK = "&OK";
/// <summary>
/// Cancel text
/// </summary>
public static string Cancel = "&Cancel";
/// <summary>
/// Abort text
/// </summary>
public static string Abort = "&Abort";
/// <summary>
/// Retry text
/// </summary>
public static string Retry = "&Retry";
/// <summary>
/// Ignore text
/// </summary>
public static string Ignore = "&Ignore";
/// <summary>
/// Yes text
/// </summary>
public static string Yes = "&Yes";
/// <summary>
/// No text
/// </summary>
public static string No = "&No";
static MessageBoxManager()
{
hookProc = new HookProc(MessageBoxHookProc);
enumProc = new EnumChildProc(MessageBoxEnumProc);
hHook = IntPtr.Zero;
}
/// <summary>
/// Enables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// MessageBoxManager functionality is enabled on current thread only.
/// Each thread that needs MessageBoxManager functionality has to call this method.
/// </remarks>
public static void Register()
{
if (hHook != IntPtr.Zero)
throw new NotSupportedException("One hook per thread allowed.");
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
/// <summary>
/// Disables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// Disables MessageBoxManager functionality on current thread only.
/// </remarks>
public static void Unregister()
{
if (hHook != IntPtr.Zero)
{
UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero;
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
return CallNextHookEx(hHook, nCode, wParam, lParam);
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == WM_INITDIALOG)
{
int nLength = GetWindowTextLength(msg.hwnd);
StringBuilder className = new StringBuilder(10);
GetClassName(msg.hwnd, className, className.Capacity);
if (className.ToString() == "#32770")
{
nButton = 0;
EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
if (nButton == 1)
{
IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
if (hButton != IntPtr.Zero)
SetWindowText(hButton, OK);
}
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
{
StringBuilder className = new StringBuilder(10);
GetClassName(hWnd, className, className.Capacity);
if (className.ToString() == "Button")
{
int ctlId = GetDlgCtrlID(hWnd);
switch (ctlId)
{
case MBOK:
SetWindowText(hWnd, OK);
break;
case MBCancel:
SetWindowText(hWnd, Cancel);
break;
case MBAbort:
SetWindowText(hWnd, Abort);
break;
case MBRetry:
SetWindowText(hWnd, Retry);
break;
case MBIgnore:
SetWindowText(hWnd, Ignore);
break;
case MBYes:
SetWindowText(hWnd, Yes);
break;
case MBNo:
SetWindowText(hWnd, No);
break;
}
nButton++;
}
return true;
}
}
}
There is another way, though more for " How can I construct the following string in an Excel formula: "Maurice "The Rocket" Richard" " than " How to create strings containing double quotes in Excel formulas? ", which is simply to use two single quotes:
On the left is Calibri snipped from an Excel worksheet and on the right a snip from a VBA window. In my view escaping as mentioned by @YonahW wins 'hands down' but two single quotes is no more typing than two doubles and the difference is reasonably apparent in VBA without additional keystrokes while, potentially, not noticeable in a spreadsheet.
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
A lot of the solutions here are elegant and pretty, but don't scale well, and are memory intensive or CPU intensive. Most are creating 2 new data points in memory with this solution from both sides of the comparison. The larger the array the harder and longer the process and memory used, and you lose the benefit of short circuit evaluation. I Did some testing with a few different ideas. Trying to avoid array_key_exists as it is costly, and also avoiding creating new large datasets to compare. I feel this is a simple way to tell if an array is sequential.
public function is_sequential( $arr = [] ){
if( !is_array( $arr ) || empty( $arr ) ) return false;
$i = 0;
$total = count( $arr );
foreach( $arr as $key => $value ) if( $key !== $i++ ) return false;
return true;
}
You run a single count on the main array and store a single integer. You then loop through the array and check for an exact match while iterating the counter. You should have from 1 to count. If it fails it will short circuit out which gives you performance boost when it is false.
Originally I did this with a for loop and checking for isset( $arr[$i] ) but this will not detect null keys which requires array_key_exists, and as we know that is the worst function to use for speed.
Constantly updating variables via foreach to check along with the iterator never growing past it's integer size let's PHP use it's built in memory optimization, caching and garbage collection to keep you at very low resource usage.
Also, I will argue that using array_keys in a foreach is silly when you can simply run $key => $value and check the key. Why create the new data point? Once you abstract away the array keys you've consumed more memory immediately.
Add the below code and it will be done.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
<script type="text/javascript">
// Mock client code for testing purpose
$(function(){
// Client should be able to add another change event to the textfield
$("input[name='input1']").blur(function(){ alert("Custom event triggered."); });
// Client should be able to set the field's styles, without affecting place holder
$("textarea[name='input4']").css("color", "red");
// Initialize placeholder
$.Placeholder.init();
// or try initialize with parameter
//$.Placeholder.init({ color : 'rgb(255, 255, 0)' });
// call this before form submit if you are submitting by JS
//$.Placeholder.cleanBeforeSubmit();
});
</script>
Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip
According to this message on the GCC mailing list, you can use the file "nul" instead of /dev/null:
#include <stdio.h>
int main ()
{
FILE* outfile = fopen ("/dev/null", "w");
if (outfile == NULL)
{
fputs ("could not open '/dev/null'", stderr);
}
outfile = fopen ("nul", "w");
if (outfile == NULL)
{
fputs ("could not open 'nul'", stderr);
}
return 0;
}
(Credits to Danny for this code; copy-pasted from his message.)
You can also use this special "nul" file through redirection.
If you are moving folders via Repository Browser, then there is no Move option on right-click; the only way is to drag and drop.
Connections have a close
method as specified in PEP-249 (Python Database API Specification v2.0):
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
conn.close() #<--- Close the connection
Since the pyodbc
connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
with conn:
crs = conn.cursor()
do_stuff
# conn.commit() will automatically be called when Python leaves the outer `with` statement
# Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!!
See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.
Note that unlike the original code, this causes conn.commit()
to be called. Use the outer with
statement to control when you want commit
to be called.
Also note that regardless of whether or not you use the with
statements, per the docs,
Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [
conn.close()
], but you can explicitly close the connection if you wish.
and similarly for cursors (my emphasis):
Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [
csr.close()
] is not usually necessary.
The Python documentation does explain it.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
I had ACL (somehow) attached to all files in the .git folder.
Check it with ls -le
in the .git folder.
You can remove the ACL with chmod -N
(for a folder/file) or chmod -RN
(recursive)
PCDATA – parsed character data. It parses all the data in an XML document.
Example:
<family>
<mother>mom</mother>
<father>dad</father>
</family>
Here, the <family>
element contains 2 more elements: <mother>
and <father>
. So it parses further to get the text of mother and father to give the text value of family as “mom dad”
CDATA – unparsed character Data. This is the data that should not be parsed further in an xml document.
<family>
<![CDATA[
<mother>mom</mother>
<father>dad</father>
]]>
</family>
Here, the text value of family will be <mother>mom</mother><father>dad</father>
.
Just a word on drawing (incorrect) conclusions from any of the performance measurement commands referred to in the answers. There are a number of pitfalls that should taken in consideration aside from looking to the bare invocation time of a (custom) function or command.
'Sjoemelsoftware' voted Dutch word of the year 2015
Sjoemelen means cheating, and the word sjoemelsoftware came into being due to the Volkswagen emissions scandal. The official definition is "software used to influence test results".
Personally, I think that "Sjoemelsoftware" is not always deliberately created to cheat test results but might originate from accommodating practical situation that are similar to test cases as shown below.
As an example, using the listed performance measurement commands, Language Integrated Query (LINQ)(1), is often qualified as the fasted way to get something done and it often is, but certainly not always! Anybody who measures a speed increase of a factor 40 or more in comparison with native PowerShell commands, is probably incorrectly measuring or drawing an incorrect conclusion.
The point is that some .Net classes (like LINQ) using a lazy evaluation (also referred to as deferred execution(2)). Meaning that when assign an expression to a variable, it almost immediately appears to be done but in fact it didn't process anything yet!
Let presume that you dot-source your . .\Dosomething.ps1
command which has either a PowerShell or a more sophisticated Linq expression (for the ease of explanation, I have directly embedded the expressions directly into the Measure-Command
):
$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}
(Measure-Command {
$PowerShell = $Data.Where{$_.Index -eq 12345}
}).totalmilliseconds
864.5237
(Measure-Command {
$Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})
}).totalmilliseconds
24.5949
The result appears obvious, the later Linq command is a about 40 times faster than the first PowerShell command. Unfortunately, it is not that simple...
Let's display the results:
PS C:\> $PowerShell
Index Property
----- --------
12345 104123841
PS C:\> $Linq
Index Property
----- --------
12345 104123841
As expected, the results are the same but if you have paid close attention, you will have noticed that it took a lot longer to display the $Linq
results then the $PowerShell
results.
Let's specifically measure that by just retrieving a property of the resulted object:
PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
14.8798
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds
1360.9435
It took about a factor 90 longer to retrieve a property of the $Linq
object then the $PowerShell
object and that was just a single object!
Also notice an other pitfall that if you do it again, certain steps might appear a lot faster then before, this is because some of the expressions have been cached.
Bottom line, if you want to compare the performance between two functions, you will need to implement them in your used case, start with a fresh PowerShell session and base your conclusion on the actual performance of the complete solution.
(1) For more background and examples on PowerShell and LINQ, I recommend tihis site: High Performance PowerShell with LINQ
(2) I think there is a minor difference between the two concepts as with lazy evaluation the result is calculated when needed as apposed to deferred execution were the result is calculated when the system is idle
<script type="text/javascript">
$("#textFileID").html("Loading...").load("URL TEXT");
</script>
<div id="textFileID"></div>