Small addition to the help above: I got the mismatch error after adding a static libto an older VST solution using VST 2017 . VST now generates "stdfax.h" for precompiled headers containing these 2 lines:
// Turn off iterator debugging as it makes the compiler very slow on large methods in debug builds
#define _HAS_ITERATOR_DEBUGGING 0
There is a new library called ipyvolume that may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)
Fast and easy with HAVING:
SELECT * FROM tblpm n
FROM tblpm GROUP BY control_number
HAVING date_updated=MAX(date_updated);
In the context of HAVING
, MAX
finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated)
. If there's a tie for latest within a group, both will pass the HAVING
filter, but GROUP BY
means that only one will appear in the returned table.
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
In Python 3.5+, encode the string to bytes and use the hex()
method, returning a string.
s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'
Optionally convert the string back to bytes:
b = bytes(s, "utf-8")
b
# b'68656c6c6f'
In my opinion, the accepted answer is confusing, since it uses a DataFrame with only missing values. I also do not like the term position-based for .iloc
and instead, prefer integer location as it is much more descriptive and exactly what .iloc
stands for. The key word is INTEGER - .iloc
needs INTEGERS.
See my extremely detailed blog series on subset selection for more
Because .ix
is deprecated we will only focus on the differences between .loc
and .iloc
.
Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each index. Let's take a look at a sample DataFrame:
df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
'height':[165, 70, 120, 80, 180, 172, 150],
'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
},
index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])
All the words in bold are the labels. The labels, age
, color
, food
, height
, score
and state
are used for the columns. The other labels, Jane
, Nick
, Aaron
, Penelope
, Dean
, Christina
, Cornelia
are used for the index.
The primary ways to select particular rows in a DataFrame are with the .loc
and .iloc
indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.
We will first talk about the .loc
indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length of the DataFrame.
There are three different inputs you can use for .loc
Selecting a single row with .loc with a string
To select a single row of data, place the index label inside of the brackets following .loc
.
df.loc['Penelope']
This returns the row of data as a Series
age 4
color white
food Apple
height 80
score 3.3
state AL
Name: Penelope, dtype: object
Selecting multiple rows with .loc with a list of strings
df.loc[['Cornelia', 'Jane', 'Dean']]
This returns a DataFrame with the rows in the order specified in the list:
Selecting multiple rows with .loc with slice notation
Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.
df.loc['Aaron':'Dean']
Complex slices can be taken in the same manner as Python lists.
Let's now turn to .iloc
. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.
There are three different inputs you can use for .iloc
Selecting a single row with .iloc with an integer
df.iloc[4]
This returns the 5th row (integer location 4) as a Series
age 32
color gray
food Cheese
height 180
score 1.8
state AK
Name: Dean, dtype: object
Selecting multiple rows with .iloc with a list of integers
df.iloc[[2, -2]]
This returns a DataFrame of the third and second to last rows:
Selecting multiple rows with .iloc with slice notation
df.iloc[:5:3]
One excellent ability of both .loc/.iloc
is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.
For example, we can select rows Jane, and Dean with just the columns height, score and state like this:
df.loc[['Jane', 'Dean'], 'height':]
This uses a list of labels for the rows and slice notation for the columns
We can naturally do similar operations with .iloc
using only integers.
df.iloc[[1,4], 2]
Nick Lamb
Dean Cheese
Name: food, dtype: object
.ix
was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.
For instance, if we want to select rows Nick
and Cornelia
along with columns 2 and 4, we could use .loc
by converting the integers to labels with the following:
col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names]
Or alternatively, convert the index labels to integers with the get_loc
index method.
labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]
The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows wher age is above 30 and return just the food
and score
columns we can do the following:
df.loc[df['age'] > 30, ['food', 'score']]
You can replicate this with .iloc
but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:
df.iloc[(df['age'] > 30).values, [2, 4]]
It is possible to use .loc/.iloc
for just column selection. You can select all the rows by using a colon like this:
df.loc[:, 'color':'score':2]
[]
, can select rows and columns too but not simultaneously.Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.
df['food']
Jane Steak
Nick Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
Using a list selects multiple columns
df[['food', 'score']]
What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.
df['Penelope':'Christina'] # slice rows by label
df[2:6:2] # slice rows by integer location
The explicitness of .loc/.iloc
for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.
df[3:5, 'color']
TypeError: unhashable type: 'slice'
I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, i.e. if you type "Hello" really quickly; instead of firing just once when you stop typing, the function would fire 5 times.
The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set. See below:
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#myInput').on("keyup", function(){
if (typingTimer) clearTimeout(typingTimer); // Clear if already set
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#myInput').on("keydown", function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
N.B. I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation. Sorry!
As another cheap alternative on somewhat static canvas, using an overlaying img element with a usemap definition is quick and dirty. Works especially well on polygon based canvas elements like a pie chart.
For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.
Just put use [DBName]
on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.
It's called an initialization list. It initializes members before the body of the constructor executes.
David Crawshaw project(sqlitejdbc-v056.jar) seems out of date and last update was Jun 20, 2009, source here
I would recomend Xerials fork of Crawshaw sqlite wrapper. I replaced sqlitejdbc-v056.jar with Xerials sqlite-jdbc-3.7.2.jar file without any problem.
Uses same syntax as in Bernie's answer and is much faster and with latest sqlite library.
What is different from Zentus's SQLite JDBC?
The original Zentus's SQLite JDBC driver http://www.zentus.com/sqlitejdbc/ itself is an excellent utility for using SQLite databases from Java language, and our SQLiteJDBC library also relies on its implementation. However, its pure-java version, which totally translates c/c++ codes of SQLite into Java, is significantly slower compared to its native version, which uses SQLite binaries compiled for each OS (win, mac, linux).
To use the native version of sqlite-jdbc, user had to set a path to the native codes (dll, jnilib, so files, which are JNDI C programs) by using command-line arguments, e.g., -Djava.library.path=(path to the dll, jnilib, etc.), or -Dorg.sqlite.lib.path, etc. This process was error-prone and bothersome to tell every user to set these variables. Our SQLiteJDBC library completely does away these inconveniences.
Another difference is that we are keeping this SQLiteJDBC libray up-to-date to the newest version of SQLite engine, because we are one of the hottest users of this library. For example, SQLite JDBC is a core component of UTGB (University of Tokyo Genome Browser) Toolkit, which is our utility to create personalized genome browsers.
EDIT : As usual when you update something, there will be problems in some obscure place in your code(happened to me). Test test test =)
you can for example: set your environment variable path with php.exe folder e.g c:\program files\php
create a script file in d:\ with filename as a.php
open cmd: go to d: drive using d: command
type following command
php -f a.php
you will see the output
Javascript has first class functions. This means that they can be treated just like any other variable. Functions can be passed as arguments in a function, be returned from a function, and can be stored in variables.
However storing function in a variable (function expression) isn't the only way to create a function, this can also be done via a function declaration. Here are the key differences:
undefined
.Here is an example:
try {_x000D_
functionOne();_x000D_
} catch (e) {_x000D_
console.log('i cant run because im not hoisted');_x000D_
}_x000D_
_x000D_
functionTwo();_x000D_
_x000D_
// function expression, does not get hoisted_x000D_
let functionOne = function randomName() {_x000D_
// Some code_x000D_
};_x000D_
_x000D_
// function declaration, gets hoisted_x000D_
function functionTwo() {_x000D_
console.log('I get hoisted');_x000D_
}_x000D_
_x000D_
try {_x000D_
randomName(); // this isn't the proper name, it is functionOne_x000D_
} catch (e) {_x000D_
console.log('You cant call me with randomName my name is function one');_x000D_
}
_x000D_
:
Just try below script:
Below code works only if studentid column datatype is varchar
SELECT * FROM STUDENTS WHERE STUDENTID like '%Searchstring%'
Re-Ordering data Table based on some condition or check box checked. PFB :-
var tableResult= $('#exampleTable').DataTable();
var $tr = $(this).closest('tr');
if ($("#chkBoxId").prop("checked"))
{
// re-draw table shorting based on condition
tableResult.row($tr).invalidate().order([colindx, 'asc']).draw();
}
else {
tableResult.row($tr).invalidate().order([colindx, "asc"]).draw();
}
Notice you can use WHEN exception THEN NULL
the same way as you would use WHEN exception THEN continue
. Example:
DECLARE
extension_already_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(extension_already_exists, -20007);
l_hidden_col_name varchar2(32);
BEGIN
FOR t IN ( SELECT table_name, cast(extension as varchar2(200)) ext
FROM all_stat_extensions
WHERE owner='{{ prev_schema }}'
and droppable='YES'
ORDER BY 1
)
LOOP
BEGIN
l_hidden_col_name := dbms_stats.create_extended_stats('{{ schema }}', t.table_name, t.ext);
EXCEPTION
WHEN extension_already_exists THEN NULL; -- ignore exception and go to next loop iteration
END;
END LOOP;
END;
Because cron is "stateless", it cannot accurately express "frequencies", only "patterns" which it (apparently) continuously matches against the current time.
Rephrasing your question makes this more obvious: "is it possible to run a cronjob at 00:01am every night except skip nights when it had run within 2 nights?" When cron is comparing the current time to job request time patterns, there's no way cron can know if it ran your job in the past.
(it certainly is possible to write a stateful cron that records past jobs and thus includes patterns for matching against this state, but that's not the standard cron included in most operating systems. Such a system would get complicated by requiring the introduction of the concept of when such patterns "reset". For example, is the pattern reset when the time is changed (i.e. the crontab entry is revised)? Look to your favorite calendar app to see how complicated it can get to express Repeating patterns of scheduled events, and note that they don't have the reset problem because the starting calendar event has a natural "start" a/k/a "reset" date. Try rescheduling an every-other-week recurring calendar event to postpone by a week, over christmas for example. Usually you have to terminate that recurring event and restart a completely new one; this illustrates the limited expressivity of how even complicated calendar apps represent repeating patterns. And of course Calendars have a lot of state-- each individual event can be deleted or rescheduled independently [in most calendar apps]).
Further, you probably want to do your job every 3rd night if successful, but if the last one failed, to try again immediately, perhaps the next night (not wait 3 more days) or even sooner, like an hour later (but stop retrying upon morning's arrival). Clearly, cron couldn't possibly know if your job succeeded and the pattern can't also express an alternate more frequent "retry" schedule.
ANYWAY-- You can do what you want yourself. Write a script, tell cron to run it nightly at 00:01am. This script could check the timestamp of something* which records the "last run", and if it was >3 days ago**, perform the job and reset the "last run" timestamp.
(*that timestamped indicator is a bit of persisted state which you can manipulate and examine, but which cron cannot)
**be careful with time arithmetic if you're using human-readable clock time-- twice a year, some days have 23 or 25 hours in their day, and 02:00-02:59 occurs twice in one day or not at all. Use UTC to avoid this.
If you want to style the subtitle also then simply add this in your custom style.
<item name="android:subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
People who are looking to get the same result for AppCompat
library then this is what I used:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomActivityTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<item name="actionBarStyle">@style/MyActionBar</item>
<!-- other activity and action bar styles here -->
</style>
<!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:background">@drawable/actionbar_background</item>
<item name="background">@drawable/actionbar_background</item>
<item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
<item name="android:subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
<item name="titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
<item name="subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
</style>
<style name="MyTheme.ActionBar.TitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/color_title</item>
</style>
</resources>
Implement the Serializable
interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable
object might reference an instance of your class.
Serializable
classes are useful when you want to persist instances of them or send them over a wire.
Instances of Serializable
classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.
Use
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
the behaviour of fixed elements (and absolute elements) as defined in CSS Spec:
They behave as they are detached from document, and placed in the nearest fixed/absolute positioned parent. (not a word by word quote)
This makes zindex calculation a bit complicated, I solved my problem (the same situation) by dynamically creating a container in body element and moving all such elements (which are class-ed as "my-fixed-ones" inside that body-level element)
Replace [ with nothing, then ] with nothing.
Just been working on something very similar, I am not an expert but I thought I would share the commands I have used. I had a multi column csv which I only required 4 columns out of and then I needed to reorder them.
My file was pipe '|' delimited but that can be swapped out.
LC_ALL=C cut -d$'|' -f1,2,3,8,10 ./file/location.txt | sed -E "s/(.*)\|(.*)\|(.*)\|(.*)\|(.*)/\3\|\5\|\1\|\2\|\4/" > ./newcsv.csv
Admittedly it is really rough and ready but it can be tweaked to suit!
From Android O, you cant use the services for the long running background operations due to this, https://developer.android.com/about/versions/oreo/background . Jobservice will be the better option with Jobscheduler implementation.
Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a>
and you should be good to go.
If you want to use it for an image, the <a>
tag can handle the <img/>
placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>
EDIT: better yet, do it like that:
var filteredProjects =
projects.Where(p => filteredTags.All(tag => p.Tags.Contains(tag)));
EDIT2: Honestly, I don't know which one is better, so if performance is not critical, choose the one you think is more readable. If it is, you'll have to benchmark it somehow.
Probably Intersect
is the way to go:
void Main()
{
var projects = new List<Project>();
projects.Add(new Project { Name = "Project1", Tags = new int[] { 2, 5, 3, 1 } });
projects.Add(new Project { Name = "Project2", Tags = new int[] { 1, 4, 7 } });
projects.Add(new Project { Name = "Project3", Tags = new int[] { 1, 7, 12, 3 } });
var filteredTags = new int []{ 1, 3 };
var filteredProjects = projects.Where(p => p.Tags.Intersect(filteredTags).Count() == filteredTags.Length);
}
class Project {
public string Name;
public int[] Tags;
}
Although that seems a little ugly at first. You may first apply Distinct
to filteredTags
if you aren't sure whether they are all unique in the list, otherwise the counts comparison won't work as expected.
The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)
To link with gdi32:
This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a
has no advantage over gdi32
other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib
for MSVC).
For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).
For OSX: pip install scikit-image
and then run python to try following
from skimage.feature import corner_harris, corner_peaks
How about this:
UPDATE p
SET p.extrasPrice = t.sumPrice
FROM BookingPitches AS p
INNER JOIN
(
SELECT PitchID, SUM(Price) sumPrice
FROM BookingPitchExtras
WHERE [required] = 1
GROUP BY PitchID
) t
ON t.PitchID = p.ID
WHERE p.bookingID = 1
You don't need initialization lists for that:
std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
The documentation is your friend, NSString
supports a call substringWithRange
that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString
it is immutable. If you have an NSMutableString
is has a method called deleteCharactersInRange
that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...
I had used JCL about 2 years back so cannot write a code for you but here is the idea;
again i apologize for solution without code, but i am out of touch by 2 yrs+
I found a short cut rather than going through vs code appData/webCompiler
, I added it as a dependency to my project with this cmd npm i caniuse-lite browserslist
. But you might install it globally to avoid adding it to each project.
After installation, you could remove it from your project package.json
and do npm i
.
Update:
In case, Above solution didn't fix it. You could run npm update
, as this would upgrade deprecated/outdated packages.
Note:
After you've run the npm update, there may be missing dependencies. Trace the error and install the missing dependencies. Mine was nodemon, which I fix by npm i nodemon -g
Simple you can change the action of form on different submit buttons Click.
Try this in document.Ready
$(".acceptOffer").click(function () {
$("form").attr("action", "/Managers/SubdomainTransactions");
});
$(".declineOffer").click(function () {
$("form").attr("action", "/Sales/SubdomainTransactions");
});
Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.
You can add Environment variable also in this process
Please check this:
$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';
$connection = mysqli_connect($servername,$username,$password);
if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}
/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");
if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}
mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");
$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/
T(N) = T(N/2) + 1
T(N) = T(N/2) + 1 = (T(N/4) + 1)+ 1
...
T(N) = T(N/N) + (1 + 1 + 1 +... + 1) = 1 + logN (base 2 log) = 1 + logN
So the time complexity of binary search is O(logN)
I have <a>
inside the <li>
s.
To the <ul>
elements, apply the following CSS:
ul {
margin: 0;
padding: 0;
list-style: none;
}
To the <a>
elements, apply the following CSS:
a:before {
content: "";
height: 6px;
width: 6px;
border-radius: 50%;
background: #000;
display: inline-block;
margin: 0 6px 0 0;
vertical-align: middle;
}
This creates pseudo elements for the bullets. They can be styled just like any other elements.
I've implemented it here: http://www.cssdesk.com/R2AvX
You need to use an anonymous function like this:
$('.leadtoscore').click(function() {
add_event('shot')
});
You can call it like you have in the example, just a function name without parameters, like this:
$('.leadtoscore').click(add_event);
But the add_event
method won't get 'shot'
as it's parameter, but rather whatever click
passes to it's callback, which is the event
object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind()
and pass data, like this:
$('.leadtoscore').bind('click', { param: 'shot' }, add_event);
And access it in add_event
, like this:
function add_event(event) {
//event.data.param == "shot", use as needed
}
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
Here is the sample of your answer: http://plnkr.co/edit/MKugkgCSpdZFefSeDRi7?p=preview
<span>Date Of Birth: {{DateOfBirth | date:"dd-MM-yyyy"}}</span>
<input type="text" datepicker-popup="dd/MM/yyyy" ng-model="DateOfBirth" class="form-control" />
and then in the controller:
$scope.DateOfBirth = new Date();
The answer appears to be solely related to application size. I created a simple "hello world" app with nothing special in the manifest file, uploaded it to the Play store, and it was reported as compatible with my device.
I changed nothing in this app except for adding more content into the res/drawable
directory. When the .apk
size reached about 32 MB, the Play store started reporting that my app was incompatible with my phone.
I will attempt to contact Google developer support and ask for clarification on the reason for this limit.
UPDATE: Here is Google developer support response to this:
Thank you for your note. Currently the maximum file size limit for an app upload to Google Play is approximately 50 MB.
However, some devices may have smaller than 50 MB cache partition making the app unavailable for users to download. For example, some of HTC Wildfire devices are known for having 35-40 MB cache partitions. If Google Play is able to identify such device that doesn't have cache large enough to store the app, it may filter it from appearing for the user.
I ended up solving my problem by converting all the PNG files to JPG, with a small loss of quality. The .apk
file is now 28 MB, which is below whatever threshold Google Play is enforcing for my phone.
I also removed all the <uses-feature>
stuff, and now have just this:
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
For me going to Edit Scheme -> Run, and changing the debug configuration to Debug from Release fix the problem.
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Using some of the answers on this page and here, I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/
You can use *args and **kwargs syntax for variable length arguments.
What do *args and **kwargs mean?
And from the official python tutorial
http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions
To simplify this actions from accepted answer, you can also create Category for UIView
(since this works for all subclasses of UIView, not only for textfields:
UIView+Additions.h:
#import <Foundation/Foundation.h>
@interface UIView (Additions)
- (void)setBorderForColor:(UIColor *)color
width:(float)width
radius:(float)radius;
@end
UIView+Additions.m:
#import "UIView+Additions.h"
@implementation UIView (Additions)
- (void)setBorderForColor:(UIColor *)color
width:(float)width
radius:(float)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = YES;
self.layer.borderColor = [color CGColor];
self.layer.borderWidth = width;
}
@end
Usage:
#import "UIView+Additions.h"
//...
[textField setBorderForColor:[UIColor redColor]
width:1.0f
radius:8.0f];
You can use timexe
It's simple to use, light weight, has no dependencies, has an improved syntax over cron, with a resolution in milliseconds and works in the browser.
Install:
npm install timexe
Use:
var timexe = require('timexe');
var res = timexe("* * * 15 30", function(){ console.log("It's now 3:30 pm"); });
(I'm the author)
The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?
Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.
Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.
Defragment the table
As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.
Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.
Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.
As stated in other answers, using a more selective query will return less data, and should be therefore be faster.
Now let's consider what we can do if we are allowed to add indexes.
If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?
Edit
I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.
I removed all indexes apart from the primary key on the Id column.
A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.
What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
I mostly use this function:
cf() {
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"
}
You could also assign a shortcut to a script like the ones below.
Reuse an existing tab or create a new window (Terminal):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
if (exists window 1) and not busy of window 1 then
do script "cd " & quoted form of p in window 1
else
do script "cd " & quoted form of p
end if
activate
end tell
Reuse an existing tab or create a new tab (Terminal):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
if not (exists window 1) then reopen
activate
if busy of window 1 then
tell application "System Events" to keystroke "t" using command down
end if
do script "cd " & quoted form of p in window 1
end tell
Always create a new tab (iTerm 2):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "iTerm"
if exists current terminal then
current terminal
else
make new terminal
end if
tell (launch session "Default") of result to write text "cd " & quoted form of p
activate
end tell
The first two scripts have two advantages compared to the services added in 10.7:
As the others said, you can't. You can find good examples of HTML-php forms on the web, here's a very useful link that combines HTML with javascript for validation and php for sending the email.
Please check the full article (includes zip example) in the source: http://www.html-form-guide.com/contact-form/php-email-contact-form.html
HTML:
<form method="post" name="contact_form"
action="contact-form-handler.php">
Your Name:
<input type="text" name="name">
Email Address:
<input type="text" name="email">
Message:
<textarea name="message"></textarea>
<input type="submit" value="Submit">
</form>
JS:
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email",
"Please enter a valid email address");
</script>
PHP:
<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
import math
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # discriminant
if d < 0:
print ("This equation has no real solution")
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print (("This equation has one solutions: "), x)
#add the extra () above or it does not show the answer just the text.
else:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
While it's true that id(object)
gets the object's address in the default CPython implementation, this is generally useless... you can't do anything with the address from pure Python code.
The only time you would actually be able to use the address is from a C extension library... in which case it is trivial to get the object's address since Python objects are always passed around as C pointers.
To get "local" yesterday in UTC.
var now = DateTime.Now;
var yesterday = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, DateTimeKind.Utc).AddDays(-1);
Here's some code with a dummy geom_blank
layer,
range_act <- range(range(results$act), range(results$pred))
d <- reshape2::melt(results, id.vars = "pred")
dummy <- data.frame(pred = range_act, value = range_act,
variable = "act", stringsAsFactors=FALSE)
ggplot(d, aes(x = pred, y = value)) +
facet_wrap(~variable, scales = "free") +
geom_point(size = 2.5) +
geom_blank(data=dummy) +
theme_bw()
Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict
>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1
For those using Python 3
>>> list(x.keys()).index("c")
1
@IanDevlin is correct. MDN's rules say the following:
"The HTML Header Element "" defines a page header — typically containing the logo and name of the site and possibly a horizontal menu..."
The word "possibly" there is key. It goes on to say that the header doesn't necessarily need to be a site header. For instance you could include a "header" on a pop-up modal or on other modular parts of the document where there is a header and it would be helpful for a user on a screen reader to know about it.
It terms of the implicit use of NAV you can use it anywhere there is grouped site navigation, although it's usually omitted from the "footer" section for mini-navs / important site links.
Really it comes down to personal / team choice. Decide what you and your team feel is more semantic and more important and the try to be consistent. For me, if the nav is inline with the logo and the main site's "h1" then it makes sense to put it in the "header" but if you have a different design choice then decide on a case by case basis.
Most importantly check out the docs and be sure if you choose to omit or include you understand why you are making that particular decision.
Posting this since React.createClass
is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.
Parent
import React, {Component} from 'react';
import Child from './Child';
export default class Parent extends Component {
es6Function = (value) => {
console.log(value)
}
simplifiedFunction (value) {
console.log(value)
}
render () {
return (
<div>
<Child
es6Function = {this.es6Function}
simplifiedFunction = {this.simplifiedFunction}
/>
</div>
)
}
}
Child
import React, {Component} from 'react';
export default class Child extends Component {
render () {
return (
<div>
<h1 onClick= { () =>
this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
}
Simplified stateless child as ES6 constant
import React from 'react';
const Child = () => {
return (
<div>
<h1 onClick= { () =>
this.props.es6Function(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
export default Child;
As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.
Place your config file into src/main/resources/app-context.xml and use code
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}
or you can make yout test context with different configuration of beans.
Place your config file into src/test/resources/test-app-context.xml and use code
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}
On your DBA account, give USERB the right to create a procedure using grant grant create any procedure to USERB
The procedure will look
CREATE OR REPLACE PROCEDURE USERB.USERB_PROCEDURE
--Must add the line below
AUTHID CURRENT_USER AS
BEGIN
--DO SOMETHING HERE
END
END
GRANT EXECUTE ON USERB.USERB_PROCEDURE TO USERA
I know this is a very old question but I am hoping I could chip it a bit.
I had the same question a couple of weeks ago and was evaluating both JSLint and JSHint.
Contrary to the answers in this question, my conclusion was not:
By all means use JSLint.
Or:
If you're looking for a very high standard for yourself or team, JSLint.
As you can configure almost the same rules in JSHint as in JSLint. So I would argue that there's not much difference in the rules you could achieve.
So the reasons to choose one over another are more political than technical.
We've finally decided to go with JSHint because of the following reasons:
Use these codes for 404 not found.
if(strstr($_SERVER['REQUEST_URI'],'index.php')){
header('HTTP/1.0 404 Not Found');
readfile('404missing.html');
exit();
}
Here 404missing.html is your Not found design page. (it can be .html or .php)
You can pass it to view but first query it in controller, and then after that add this :
return view('yourview', COMPACT('variabelnametobepassedtoview'));
The stringr
package provides the str_sub
function, which is a bit easier to use than substr
, especially if you want to extract right portions of your string :
R> str_sub("leftright",1,4)
[1] "left"
R> str_sub("leftright",-5,-1)
[1] "right"
it seems you can directly call:
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g._legend.set_bbox_to_anchor((.7, 1.1))
why dont you do something like:
re = /^[a-z0-9 ]$/i;
var isValid = re.test(yourInput);
to check if your input contain any special char
the fastest way seems to be a lookup table for masks
I routinely use several Anaconda-installed virtual environments (venv). This code snippet/examples enables you to determine whether or not you are in a venv (or your system environment), and to also require a specific venv for your script.
Add to Python script (code snippet):
# ----------------------------------------------------------------------------
# Want script to run in Python 3.5 (has required installed OpenCV, imutils, ... packages):
import os
# First, see if we are in a conda venv { py27: Python 2.7 | py35: Python 3.5 | tf: TensorFlow | thee : Theano }
try:
os.environ["CONDA_DEFAULT_ENV"]
except KeyError:
print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
exit()
# If we are in a conda venv, require the p3 venv:
if os.environ['CONDA_DEFAULT_ENV'] != "py35":
print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
exit()
# See also:
# Python: Determine if running inside virtualenv
# http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv
# [ ... SNIP! ... ]
Example:
$ p2
[Anaconda Python 2.7 venv (source activate py27)]
(py27) $ python webcam_.py
Please set the py35 { p3 | Python 3.5 } environment!
(py27) $ p3
[Anaconda Python 3.5 venv (source activate py35)]
(py35) $ python webcam.py -n50
current env: py35
processing (live): found 2 faces and 4 eyes in this frame
threaded OpenCV implementation
num_frames: 50
webcam -- approx. FPS: 18.59
Found 2 faces and 4 eyes!
(py35) $
Update 1 -- use in bash scripts:
You can also use this approach in bash scripts (e.g., those that must run in a specific virtual environment). Example (added to bash script):
if [ $CONDA_DEFAULT_ENV ] ## << note the spaces (important in BASH)!
then
printf 'venv: operating in tf-env, proceed ...'
else
printf 'Note: must run this script in tf-env venv'
exit
fi
Update 2 [Nov 2019]
Since my original post I've moved on from Anaconda venv (and Python itself has evolved viz-a-viz virtual environments).
Reexamining this issue, here is some updated Python code that you can insert to test that you are operating in a specific Python virtual environment (venv).
import os, re
try:
if re.search('py37', os.environ['VIRTUAL_ENV']):
pass
except KeyError:
print("\n\tPlease set the Python3 venv [alias: p3]!\n")
exit()
Here is some explanatory code.
[victoria@victoria ~]$ date; python --version
Thu 14 Nov 2019 11:27:02 AM PST
Python 3.8.0
[victoria@victoria ~]$ python
Python 3.8.0 (default, Oct 23 2019, 18:51:26)
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, re
>>> re.search('py37', os.environ['VIRTUAL_ENV'])
<re.Match object; span=(20, 24), match='py37'>
>>> try:
... if re.search('py37', os.environ['VIRTUAL_ENV']):
... print('\n\tOperating in Python3 venv, please proceed! :-)')
... except KeyError:
... print("\n\tPlease set the Python3 venv [alias: p3]!\n")
...
Please set the Python3 venv [alias: p3]!
>>> [Ctrl-d]
now exiting EditableBufferInteractiveConsole...
[victoria@victoria ~]$ p3
[Python 3.7 venv (source activate py37)]
(py37) [victoria@victoria ~]$ python --version
Python 3.8.0
(py37) [victoria@victoria ~]$ env | grep -i virtual
VIRTUAL_ENV=/home/victoria/venv/py37
(py37) [victoria@victoria ~]$ python
Python 3.8.0 (default, Oct 23 2019, 18:51:26)
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, re
>>> try:
... if re.search('py37', os.environ['VIRTUAL_ENV']):
... print('\n\tOperating in Python3 venv, please proceed! :-)')
... except KeyError:
... print("\n\tPlease set the Python3 venv [alias: p3]!\n")
...
Operating in Python3 venv, please proceed! :-)
>>>
There is always sys.exit()
.
The system library in Python's core library has an exit function which is super handy when prototyping. The code would be along the lines of:
import sys
while True:
selection = raw_input("U: Create User\nQ: Quit")
if selection is "Q" or selection is "q":
print("Quitting")
sys.exit()
if selection is "U" or selection is "u":
print("User")
#do_something()
Function using the approaches of Travis J, JLewkovich and Nick Craver...
// NOTE: Clears residual validation errors from the library "jquery.validate.js".
// By Travis J and Questor
// [Ref.: https://stackoverflow.com/a/16025232/3223785 ]
function clearJqValidErrors(formElement) {
// NOTE: Internal "$.validator" is exposed through "$(form).validate()". By Travis J
var validator = $(formElement).validate();
// NOTE: Iterate through named elements inside of the form, and mark them as
// error free. By Travis J
$(":input", formElement).each(function () {
// NOTE: Get all form elements (input, textarea and select) using JQuery. By Questor
// [Refs.: https://stackoverflow.com/a/12862623/3223785 ,
// https://api.jquery.com/input-selector/ ]
validator.successList.push(this); // mark as error free
validator.showErrors(); // remove error messages if present
});
validator.resetForm(); // remove error class on name elements and clear history
validator.reset(); // remove all error and success data
// NOTE: For those using bootstrap, there are cases where resetForm() does not
// clear all the instances of ".error" on the child elements of the form. This
// will leave residual CSS like red text color unless you call ".removeClass()".
// By JLewkovich and Nick Craver
// [Ref.: https://stackoverflow.com/a/2086348/3223785 ,
// https://stackoverflow.com/a/2086363/3223785 ]
$(formElement).find("label.error").hide();
$(formElement).find(".error").removeClass("error");
}
clearJqValidErrors($("#some_form_id"));
This related question's answer provided the solution for me... it was just a dumb mistake:
Remember to commit first!
https://stackoverflow.com/a/7572252
If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.
As others have mentioned in this and other similar threads, the best way to avoid this problem is to use RGBA/HSLA or else use a transparent PNG.
But, if you want a ridiculous solution, similar to the one linked in another answer in this thread (which is also my website), here's a brand new script I wrote that fixes this problem automatically, called thatsNotYoChild.js:
http://www.impressivewebs.com/fixing-parent-child-opacity/
Basically it uses JavaScript to remove all children from the parent div, then reposition the child elements back to where they should be without actually being children of that element anymore.
To me, this should be a last resort, but I thought it would be fun to write something that did this, if anyone wants to do this.
The jQuery docs for text()
says
Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
I'd use $td.html()
instead.
You can also use
./gradlew clean build
(Mac and Linux) -With ./
gradlew clean build
(Windows) -Without ./
it removes build folder, as well configure your modules and then build your project.
i use it before release any new app on playstore.
Sometimes a simple message in the status bar is enough:
This is very simple to implement:
Dim x As Integer
Dim MyTimer As Double
'Change this loop as needed.
For x = 1 To 50
' Do stuff
Application.StatusBar = "Progress: " & x & " of 50: " & Format(x / 50, "0%")
Next x
Application.StatusBar = False
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
you can set the environment variable JAVA_TOOL_OPTS like as follows, which will be picked by JVM for any application.
set JAVA_TOOL_OPTS=-Djava.net.preferIPv4Stack=true
You can set this from the command prompt or set in system environment variables, based on your need. Note that this will reflect into all the java applications that run in your machine, even if it's a java interpreter that you have in a private setup.
I know that we are (n-1) * (n times), but why the division by 2?
It's only (n - 1) * n
if you use a naive bubblesort. You can get a significant savings if you notice the following:
After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.
After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.
Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + ...
. This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.
Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.
Just to include the latest update (UPDATE 4) in @Arhimed 's immaculate answer in the very good summary of @sulai:
void doTheTask(AsyncTask task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Android 4.4 (API 19) and above
// Parallel AsyncTasks are possible, with the thread-pool size dependent on device
// hardware
task.execute(params);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Android 3.0 to
// Android 4.3
// Parallel AsyncTasks are not possible unless using executeOnExecutor
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else { // Below Android 3.0
// Parallel AsyncTasks are possible, with fixed thread-pool size
task.execute(params);
}
}
You can do it more simply, guaranteeing that your .gitconfig
is left in a meaningful state:
git push -u hub master
when pushing, or:
git branch -u hub/master
(This will set the remote for the currently checked-out branch to hub/master
)
git branch --set-upstream-to hub/master
(This will set the remote for the branch named branch_name
to hub/master
)
git branch branch_name --set-upstream-to hub/master
v1.7.x
or earlieryou must use --set-upstream
:
git branch --set-upstream master hub/master
Try this:
jsonResponse = json.loads(response.decode('utf-8'))
This will do the trick
.gallery-item
{
opacity:1;
}
.gallery-item:hover
{
opacity:0;
transition: opacity .2s ease-out;
-moz-transition: opacity .2s ease-out;
-webkit-transition: opacity .2s ease-out;
-o-transition: opacity .2s ease-out;
}
You've accidentally set "Pause on Exceptions" to all/uncaught exceptions.
Go to the "Sources" tab. At the bottom toolbar, toggle the button that looks like the pause symbol surrounded by a circle (4th button from the left) until the color of the circle turns black to turn it off.
If you need to support IE11 and (old) Edge, you can use:
scrollToBottom() {
let element = document.getElementById("yourID");
element.scrollIntoView(false);
}
If you don't need to support IE11, the following will work (clearer code):
scrollToBottom() {
let element = document.getElementById("yourID");
element.scrollIntoView({behavior: "smooth", block: "end"});
}
You can use Array.forEach
var myArray = ['1','2',3,4]_x000D_
_x000D_
myArray.forEach(function(value){_x000D_
console.log(value);_x000D_
});
_x000D_
Faced similar issue with my Angular Node Server(v6.10.3) which set up in WIndows 10.
http://localhost:4201
worked fine in localhost. But http://{ipaddress}:4201
not working in other machines in local network.
For this I updated the ng serve
like this
//Older ng serve in windows command Prompt
ng serve --host localhost --port 4201
//Updated ng serve
//ng serve --host {ipaddress} --port {portno}
ng serve --host 192.168.1.104 --port 4201
After doing this modification able to access my application in other machines in network bt calling this url
http://192.168.1.104:4201
//http://{ipaddress}:4201
A modified version of above solution to make it more dynamic.
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
On Error GoTo Failed
DownloadFileA = False
'As directory must exist, this is a check
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
Dim returnValue As Long
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
'If return value is 0 and the file exist, then it is considered as downloaded correctly
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
Exit Function
Failed:
End Function
I also had the same issue when I tried to install a Windows service, in my case I managed to resolved the issue by removing blank spaces in the folder path to the service .exe, below is the command worked for me in a command prompt
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Press ENTER to change working directory
InstallUtil.exe C:\MyService\Release\ReminderService.exe
Press ENTER
I've just come up with the following which is looking good in Django 1.8
Try this instead of value is not False:
if value|stringformat:'r' != 'False'
Try this instead of value is True:
if value|stringformat:'r' == 'True'
unless you've been really messing with repr methods to make value look like a boolean I reckon this should give you a firm enough assurance that value is True or False.
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
You could use PHP constant:
$array = explode(PHP_EOL, $text);
additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution
Funny the answer is hidden in among the answers.
str.replace("•", "something")
would work if you use the right semantics.
str.replace(u"\u2022","something")
works wonders ;) , thnx to RParadox for the hint.
In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.
Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:
$ ps -ef|grep httpd
0 681 1 0 10:38pm ?? 0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501 690 681 0 10:38pm ?? 0:00.02 /Applications/MAMP/Library/bin/httpd -k start
...
Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)
$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.
Wait for crash... then:
(gdb) backtrace
Or
(gdb) backtrace full
Should give you some clue what's going on. If you file a bug report you should include the backtrace.
If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:
StartServers 1
MinSpareServers 1
MaxSpareServers 1
Because you're encapsulating the product again. Try to convert it like so:
let body = JSON.stringify(product);
Unfortunately, we do not have a "TRUNCATE TABLE" command in SQLite, but you can use SQLite's DELETE
command to delete the complete data from an existing table, though it is recommended to use the DROP TABLE
command to drop the complete table and re-create it once again.
If you are on Ubuntu,
sudo su postgres
pg_dump -d <database_name> -t <table_name> > file.sql
Make sure that you are executing the command where the postgres
user have write permissions (Example: /tmp
)
Edit
If you want to dump the .sql in another computer, you may need to consider skipping the owner information getting saved into the .sql file.
You can use pg_dump --no-owner -d <database_name> -t <table_name> > file.sql
Slight modification to the answer by @pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
Just define:
#define M_PI acos(-1.0)
It should give you exact PI number that math functions are working with. So if they change PI value they are working with in tangent or cosine or sine, then your program should be always up-to-dated ;)
No. It's going to be quite a big effort to port a browser environment to node.
Another approach, that I'm currently investigating for unit testing, is to create "Mock" version of jQuery that provides callbacks whenever a selector is called.
This way you could unit test your jQuery plugins without actually having a DOM. You'll still have to test in real browsers to see if your code works in the wild, but if you discover browser specific issues, you can easily "mock" those in your unit tests as well.
I'll push something to github.com/felixge once it's ready to show.
The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..
But if you're not using 5.3, then the function below should work accurately:
function strbstr( $str, $char, $start=0 ){
if ( isset($str[ $start ]) && $str[$start]!=$char ){
return $str[$start].strbstr( $str, $char, $start+1 );
}
}
I haven't tested it though, but this should work just fine.. And it's pretty fast as well
easy_install BeautifulSoup4
or
easy_install BeautifulSoup
to install easy_install
http://pypi.python.org/pypi/setuptools#files
Updated list as of 6/11/2013
204.15.20.0/22
69.63.176.0/20
66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20
Use the :checked selector to determine if a value is selected:
function getRadioValue () {
if( $('input[name=myradiobutton]:radio:checked').length > 0 ) {
return $('input[name=myradiobutton]:radio:checked').val();
}
else {
return 0;
}
}
Update you can call the function above at any time to get the selected value of the radio buttons. You can hook into it on load and then whenever the value changes with the following events:
$(document).ready( function() {
// Value when you load the page for the first time
// Will return 0 the first time it's called
var radio_button_value = getRadioValue();
$('input[name=myradiobutton]:radio').click( function() {
// Will get the newly selected value
radio_button_value = getRadioValue();
});
}
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/array_name"
/>
You should be able to access the document in the IFRAME using the following code:
document.getElementById('myframe').contentWindow.document
However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
In my case I forgot to enable
app.use(express.json());
in my NodeJs server.
Bootstrap now has the following style for table cells:
.table tbody > tr > td{
vertical-align: top;
}
The way to go is to add your own class, adding more specificity to the previous selector:
.table tbody > tr > td.vert-aligned {
vertical-align: middle;
}
And then add the class to your td
s:
<tr>
<td class="vert-aligned"></td>
...
</tr>
There is no way to do this with Bootstrap.
When used in table cells, vertical-align does what most people expect it to, which is to mimic the (old, deprecated) valign attribute. In a modern, standards-compliant browser, the following three code snippets do the same thing:
<td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
<td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
Check your fiddle updated
Also, you can't refer to the td
class using .vert
because Bootstrap already has this class:
.table td {
padding: 8px;
line-height: 20px;
text-align: left;
vertical-align: top; // The problem!
border-top: 1px solid #dddddd;
}
And is overloading the vertical-align: middle
in '.vert' class, so you have to define this class as td.vert
.
If you're hosting a react app via AWS Static S3 Hosting & CloudFront
This problem presented itself by CloudFront responding with a 403 Access Denied message because it expected /some/other/path to exist in my S3 folder, but that path only exists internally in React's routing with react-router.
The solution was to set up a distribution Error Pages rule. Go to the CloudFront settings and choose your distribution. Next go to the "Error Pages" tab. Click "Create Custom Error Response" and add an entry for 403 since that's the error status code we get. Set the Response Page Path to /index.html and the status code to 200. The end result astonishes me with its simplicity. The index page is served, but the URL is preserved in the browser, so once the react app loads, it detects the URL path and navigates to the desired route.
The List (unlike the Set) is an ordered collection and iterating over it does preserve the order by contract. I would have expected a Stack to iterate in the reverse order but unfortunately it doesn't. So the simplest solution I can think of is this:
for (int i = stack.size() - 1; i >= 0; i--) {
System.out.println(stack.get(i));
}
I realize that this is not a "for each" loop solution. I'd rather use the for loop than introducing a new library like the Google Collections.
Collections.reverse() also does the job but it updates the list as opposed to returning a copy in reverse order.
You can retrieve the value of an attribute by its name, enabling you to get the value of a custom attribute such as an attribute from a Directive:
<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>
toggle( event: Event ) {
const eventTarget: Element = event.target as Element;
const elementId: string = eventTarget.id;
const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}
I had similar issue with width property. I couldnt remove the !important from code, and since it needed this style on a new template I added an Id (modalstyling) to the element and afterwards i added following code to the template:
<script type="text/javascript">
$('#modalstyling').css('width', ''); //Removal of width !important
$('#modalstyling').width('75%'); //Set custom width
</script>
When I added the proxy info to the %JAVA_OPTS%, I got an error "-Dhttp.proxyHost=yourserver was unexpected at this time". I put the proxy info in %SBT_OPTS% and it worked.
Previous answers are correct but here is one more way of doing this and some tips:
Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there
Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh
things to watch for /tips:
This answer mentions Json.NET but stops short of telling you how you can use Json.NET to serialize a dictionary:
return JsonConvert.SerializeObject( myDictionary );
As opposed to JavaScriptSerializer, myDictionary
does not have to be a dictionary of type <string, string>
for JsonConvert to work.
Even array2.extend(array1)
will work.
Import Router
and ActivatedRoute
from @angular/router
import { ActivatedRoute, Router } from '@angular/router';
Inject Router
and ActivatedRoute
(in case you need anything from the URL)
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
Get any parameter if needed from URL.
const appointmentId = this.route.snapshot.paramMap.get('appointmentIdentifier');
Using a trick by navigating to a dummy or main url then to the actual url will refresh the component.
this.router.navigateByUrl('/appointments', { skipLocationChange: true }).then(() => {
this.router.navigate([`appointment/${appointmentId}`])
});
const id= this.route.snapshot.paramMap.get('id');
this.router.navigateByUrl('/departments', { skipLocationChange: true }).then(() => {
this.router.navigate([`departments/${id}/employees`]);
});
If you use a dummy route then you will see a title blink 'Not Found' if you have implemented a not found url in case does not match any url.
Use pathlib.
Python 3.5 and above:
from pathlib import Path
contents = Path(file_path).read_text()
For lower versions of Python use pathlib2:
$ pip install pathlib2
Then
from pathlib2 import Path
contents = Path(file_path).read_text()
Writing is just as easy:
Path(file_path).write_text('my text')
This works. Tested.
.popover {
top: 71px !important;
left: 379px !important;
}
Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
There are lots of mathy examples here, but you wanted a real world example, so with a bit of thinking, this is possibly the best I can offer:
You find a person who has contracted a given contageous infection, which is non fatal, and fixes itself quickly( Type A) , Except for one in 5 people ( We'll call these type B ) who become permanently infected with it and shows no symptoms and merely acts a spreader.
This creates quite annoying waves of havoc when ever type B infects a multitude of type A.
Your task is to track down all the type Bs and immunise them to stop the backbone of the disease. Unfortunately tho, you cant administer a nationwide cure to all, because the people who are typeAs are also deadly allergic to the cure that works for type B.
The way you would do this, would be social discovery, given an infected person(Type A), choose all their contacts in the last week, marking each contact on a heap. When you test a person is infected, add them to the "follow up" queue. When a person is a type B, add them to the "follow up" at the head ( because you want to stop this fast ).
After processing a given person, select the person from the front of the queue and apply immunization if needed. Get all their contacts previously unvisited, and then test to see if they're infected.
Repeat until the queue of infected people becomes 0, and then wait for another outbreak..
( Ok, this is a bit iterative, but its an iterative way of solving a recursive problem, in this case, breadth first traversal of a population base trying to discover likely paths to problems, and besides, iterative solutions are often faster and more effective, and I compulsively remove recursion everywhere so much its become instinctive. .... dammit! )
A very belated answer, but I created a Windows Batch file called pythonbat.bat
containing the following:
python.exe %1
@echo off
echo.
pause
and then specified pythonbat.bat
as the default handler for .py
files.
Now, when I double-click a .py
file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...
No changes required to any Python scripts.
I can still open a console window and specify python myscript.py
if I want to...
(I just noticed @maurizio already posted this exact answer)
Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.
class Dependency{
public void method(){};
}
public abstract class My {
private Dependency dependency;
public abstract boolean myAbstractMethod();
public void myNonAbstractMethod() {
// ...
dependency.method();
}
}
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@InjectMocks
private My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
// we can mock dependencies also here
@Mock
private Dependency dependency;
@Test
private void shouldPass() {
// can be mock the dependency object here.
// It will be useful to test non abstract method
my.myNonAbstractMethod();
}
}
It will be fixed 64 chars, so use char(64)
we can find length of array by using array_name.length attribute
int [] i = i.length;
What worked for me :
$where = '';
/* $this->db->like('ust.title',$query_data['search'])
->or_like('usr.f_name',$query_data['search'])
->or_like('usr.l_name',$query_data['search']);*/
$where .= "(ust.title like '%".$query_data['search']."%'";
$where .= " or usr.f_name like '%".$query_data['search']."%'";
$where .= "or usr.l_name like '%".$query_data['search']."%')";
$this->db->where($where);
$datas = $this->db->join(TBL_USERS.' AS usr','ust.user_id=usr.id')
->where_in('ust.id', $blog_list)
->select('ust.*,usr.f_name as f_name,usr.email as email,usr.avatar as avatar, usr.sex as sex')
->get_where(TBL_GURU_BLOG.' AS ust',[
'ust.deleted_at' => NULL,
'ust.status' => 1,
]);
I have to do this to create a query like this :
SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;
Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.
In 2.3.2 the collapse
class wasn't getting replaced by the in
class. The in
class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse
class correctly is removed, and the <tr>
collapses.
Use @Chad's solution for the html, and try using these links for referencing Bootstrap:
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);
Try this:
// MARK: Reload TableView
func reloadTableView(){
tableView.reload()
}
The best practice is selecting the most appropriate one.
.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.
The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.
Reference : Here
For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.
Reference : Here
Check the source code (Reference Source .NET Framework 4.6.2)
[Pure]
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
[Pure]
public static bool IsNullOrWhiteSpace(String value) {
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
Examples
string nullString = null;
string emptyString = "";
string whitespaceString = " ";
string nonEmptyString = "abc123";
bool result;
result = String.IsNullOrEmpty(nullString); // true
result = String.IsNullOrEmpty(emptyString); // true
result = String.IsNullOrEmpty(whitespaceString); // false
result = String.IsNullOrEmpty(nonEmptyString); // false
result = String.IsNullOrWhiteSpace(nullString); // true
result = String.IsNullOrWhiteSpace(emptyString); // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString); // false
Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --
I don't like setting position using css()
, though often it's fine. I think the best bet is to use jQuery UI's position()
setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:
const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
left: baseOffset.left + leftOffset,
top: baseOffset.top + topOffset
});
This has the advantage of not arbitrarily setting $div
's parent to relative positioning (what if $div
's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div
doesn't have any offsetParent
, not sure if it would return document
, null
, or something else entirely.
offsetParent
has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.
If you haven't push the deletion yet, you can simply do :
$ git checkout deletedBranchName
sqlCommand.CommandType = CommandType.Text
@
and not ?
try this:
Public Function InsertCar() As Boolean
Dim iReturn as boolean
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO members_car (`car_id`, `member_id`, `model`, `color`, `chassis_id`, `plate_number`, `code`) values (@xid,@m_id,@imodel,@icolor,@ch_id,@pt_num,@icode)"
.Connection = SQLConnection
.CommandType = CommandType.Text // You missed this line
.Parameters.AddWithValue("@xid", TextBox20.Text)
.Parameters.AddWithValue("@m_id", TextBox20.Text)
.Parameters.AddWithValue("@imodel", TextBox23.Text)
.Parameters.AddWithValue("@icolor", TextBox24.Text)
.Parameters.AddWithValue("@ch_id", TextBox22.Text)
.Parameters.AddWithValue("@pt_num", TextBox21.Text)
.Parameters.AddWithValue("@icode", ComboBox1.SelectedItem)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = TRUE
Catch ex As MySqlException
MsgBox ex.Message.ToString
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return iReturn
End Function
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
sudo touch /var/lib/mysql/.force_upgrade
sudo rcmysql restart
worked for me when I had this issue
.foo {
position : relative;
}
.foo .wrapper {
background-image : url('semi-trans.png');
z-index : 10;
position : absolute;
top : 0;
left : 0;
}
<div class="foo">
<img src="example.png" />
<div class="wrapper"> </div>
</div>
A _ttoi
function can convert CString
to integer, both wide char and ansi char can work. Below is the details:
CString str = _T("123");
int i = _ttoi(str);
You are posting the data, so it should be $_POST. But 'name' is not the best name to use.
name = "name"
will only cause confusion IMO.
That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello"
is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello"
everywhere. The header is just a hint of what format to use when reading the .py
file.
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysql_query("select userip from pageview where page='yourpage' and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{
}
else
{
$insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");
$updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}
code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php
It sounds like something like the below will suit your needs:
With Sheets("Sheet1")
.Rows( X & ":" & .Rows.Count).Delete
End With
Where X is a variable that = the row number ( 415 )
To gzip up your font files as well!
add "x-font/otf x-font/ttf x-font/eot"
as in:
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
You could try out the following code snippet:
private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
Point center = new Point(
MenuPanel.Size.Width / 2 - control.Width * 2,
height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);
return center;
}
It's Really Center
Option 1: Put this in your procedure to print 'comment' to stdout when it runs.
SELECT 'Comment';
Option 2: Put this in your procedure to print a variable with it to stdout:
declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);
This prints myvar is 5
to stdout when the procedure runs.
Option 3, Create a table with one text column called tmptable
, and push messages to it:
declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);
You could put the above in a stored procedure, so all you would have to write is this:
CALL log(concat('the value is', myvar));
Which saves a few keystrokes.
Option 4, Log messages to file
select "penguin" as log into outfile '/tmp/result.txt';
There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.
Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now
"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "
Currently, i prefer using this methods:
String data = "Date from Register: ";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// Verify that OS.Version is > API 26 (OREO)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Origin format
LocalDate localDate = LocalDate.parse(capitalModels.get(position).getDataServer(), formatter); // Parse String (from server) to LocalDate
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
//Output format
data = "Data de Registro: "+formatter1.format(localDate); // Output
Toast.makeText(holder.itemView.getContext(), data, Toast.LENGTH_LONG).show();
}else{
//Same resolutions, just use legacy methods to oldest android OS versions.
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd",Locale.getDefault());
try {
Date date = format.parse(capitalModels.get(position).getDataServer());
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
data = "Date from Register: "+formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
double degree = fmodf((atan2(x, y) * (180.0 / M_PI)) + 360, 360);
This will return degree from 0°-360° counter-clockwise, 0° is at 3 o'clock.
Rails drop down using has_many association for article and category:
has_many :articles
belongs_to :category
<%= form.select :category_id,Category.all.pluck(:name,:id),{prompt:'select'},{class: "form-control"}%>
SELECT convert(datetime, '23/07/2009', 103)
With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions
attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
namespace ExceptionCatching
{
public class Test
{
public void StackOverflow()
{
StackOverflow();
}
public void CustomException()
{
throw new Exception();
}
public unsafe void AccessViolation()
{
byte b = *(byte*)(8762765876);
}
}
class Program
{
[HandleProcessCorruptedStateExceptions]
static void Main(string[] args)
{
Test test = new Test();
try {
//test.StackOverflow();
test.AccessViolation();
//test.CustomException();
}
catch
{
Console.WriteLine("Caught.");
}
Console.WriteLine("End of program");
}
}
}
android:scaleType ="centerInside" --> this line use to center an image,, but you need to keep height and width of an image as wrap_context
<ImageView
android:id ="@+id/imageView6"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:scaleType ="centerInside"
android:layout_marginTop ="20dp"
app:srcCompat ="@drawable/myimage" />
How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.
There is also a DataTable.ReadXml method.
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
convertToArray(file_get_content($filename));
function convertToArray(string $content): array
{
$data = str_getcsv($content,"\n");
array_walk($data, function(&$a) use ($data) {
$a = str_getcsv($a);
});
return $data;
}
if you need to close your application from main() you can use this code
int main(int argc, char *argv[]){
QApplication app(argc, argv);
...
if(!QSslSocket::supportsSsl()) return app.exit(0);
...
return app.exec();
}
The program will terminated if OpenSSL is not installed
//Function for inverse of the input square matrix 'J' of dimension 'dim':
vector<vector<double > > inverseVec33(vector<vector<double > > J, int dim)
{
//Matrix of Minors
vector<vector<double > > invJ(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
for(int j=0; j<dim; j++)
{
invJ[i][j] = (J[(i+1)%dim][(j+1)%dim]*J[(i+2)%dim][(j+2)%dim] -
J[(i+2)%dim][(j+1)%dim]*J[(i+1)%dim][(j+2)%dim]);
}
}
//determinant of the matrix:
double detJ = 0.0;
for(int j=0; j<dim; j++)
{ detJ += J[0][j]*invJ[0][j];}
//Inverse of the given matrix.
vector<vector<double > > invJT(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
for(int j=0; j<dim; j++)
{
invJT[i][j] = invJ[j][i]/detJ;
}
}
return invJT;
}
void main()
{
//given matrix:
vector<vector<double > > Jac(3,vector<double > (3));
Jac[0][0] = 1; Jac[0][1] = 2; Jac[0][2] = 6;
Jac[1][0] = -3; Jac[1][1] = 4; Jac[1][2] = 3;
Jac[2][0] = 5; Jac[2][1] = 1; Jac[2][2] = -4;`
//Inverse of the matrix Jac:
vector<vector<double > > JacI(3,vector<double > (3));
//call function and store inverse of J as JacI:
JacI = inverseVec33(Jac,3);
}
Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.
At the moment, the only unique index you have is a compound one on ISBN, Title
which is your primary key.
There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.
I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.
If you need to keep your primary key as ISBN, Title
then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.
More generally, you need to make sure that the column or columns you have in your REFERENCES
clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title
alone.
#!/usr/bin/python
# encoding=utf8
Try This to starting of python file
It's simple. Just do this:
#include <iostream>
#include <vector>
#include <string.h>
int main(int argc, char *argv[])
{
std::vector<std::string> argList;
for(int i=0;i<argc;i++)
argList.push_back(argv[i]);
//now you can access argList[n]
}
@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.
How about a fully functional implementation of a non-recursive Linked List?
I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.
Here's the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements Iterable<T> {
private Node first;
private Node last;
private int N;
public LinkedList() {
first = null;
last = null;
N = 0;
}
public void add(T item) {
if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
if (!isEmpty()) {
Node prev = last;
last = new Node(item, null);
prev.next = last;
}
else {
last = new Node(item, null);
first = last;
}
N++;
}
public boolean remove(T item) {
if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
boolean result = false;
Node prev = first;
Node curr = first;
while (curr.next != null || curr == last) {
if (curr.data.equals(item)) {
// remove the last remaining element
if (N == 1) { first = null; last = null; }
// remove first element
else if (curr.equals(first)) { first = first.next; }
// remove last element
else if (curr.equals(last)) { last = prev; last.next = null; }
// remove element
else { prev.next = curr.next; }
N--;
result = true;
break;
}
prev = curr;
curr = prev.next;
}
return result;
}
public int size() {
return N;
}
public boolean isEmpty() {
return N == 0;
}
private class Node {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
public Iterator<T> iterator() { return new LinkedListIterator(); }
private class LinkedListIterator implements Iterator<T> {
private Node current = first;
public T next() {
if (!hasNext()) { throw new NoSuchElementException(); }
T item = current.data;
current = current.next;
return item;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
}
@Override public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
while(!StdIn.isEmpty()) {
String input = StdIn.readString();
if (input.equals("print")) { StdOut.println(list.toString()); continue; }
if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
break;
}
}
}
Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.
If you want you could also look into implementing:
Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.
The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.
There are 3 commands to test this in the debugger/console:
If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:
While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.
System.Reflection.Assembly.GetAssembly(type).Location
IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO
namespace to get the exact path of the file.
For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant
. There's a tutorial, or you could just dive straight in:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>
PyEnchant
comes with a few dictionaries (en_GB, en_US, de_DE, fr_FR), but can use any of the OpenOffice ones if you want more languages.
There appears to be a pluralisation library called inflect
, but I've no idea whether it's any good.
In Java 8:
scheduler = Executors.newScheduledThreadPool(1);
//Change here for the hour you want ----------------------------------.at()
Long midnight=LocalDateTime.now().until(LocalDate.now().plusDays(1).atStartOfDay(), ChronoUnit.MINUTES);
scheduler.scheduleAtFixedRate(this, midnight, 1440, TimeUnit.MINUTES);
Have your tried using the 'return' keyword?
def rps():
return True
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
Prints this output:
Anna Mills
Female
18
If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.
function checkIfArrayIsUnique(myArray)
{
isUnique=true
for (var i = 0; i < myArray.length; i++)
{
for (var j = 0; j < myArray.length; j++)
{
if (i != j)
{
if (myArray[i] == myArray[j])
{
isUnique=false
}
}
}
}
return isUnique;
}
This assume that the array is unique at the start.
If find two equals values, then change to false
Emacs has comment-dwim (Do What I Mean) - just select the block and do a:
M-;
It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).
Just to add some performance insights.
A few years ago I had a project, where we had issues trying to set a large HTML / Text to various HTML elements.
It appeared, that "recreating" the element and injecting it to the DOM was way faster than any of the suggested methods to update the DOM content.
So something like:
var text = "very big content";_x000D_
$("#regTitle").remove();_x000D_
$("<div id='regTitle'>" + text + "</div>").appendTo("body");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Should get you a better performance. I haven't recently tried to measure that (browsers should be clever these days), but if you're looking for performance it may help.
The downside is that you will have more work to keep the DOM and the references in your scripts pointing to the right object.
My solution based on Mahdi Hijazi answer, but without any custom views:
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:id="@+id/scrollVertical"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<WateverViewYouWant/>
</ScrollView>
</HorizontalScrollView>
final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener
private float mx, my, curX, curY;
private boolean started = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
curX = event.getX();
curY = event.getY();
int dx = (int) (mx - curX);
int dy = (int) (my - curY);
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (started) {
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
} else {
started = true;
}
mx = curX;
my = curY;
break;
case MotionEvent.ACTION_UP:
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
started = false;
break;
}
return true;
}
});
You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.
This worked for for me: getResources().openRawResource(R.raw.certificate)
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
This worked for me:
position: absolute;
left: 50%;
transform: translateX(-50%);
If you'd like to do it for all dialogs throughout the site try the following code...
$.extend( $.ui.dialog.prototype.options, {
open: function() {
var dialog = this;
$('.ui-widget-overlay').bind('click', function() {
$(dialog).dialog('close');
});
}
});
I have tried your example and it works just fine:
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/test',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: {application: app, from: d1, to: d2}
});
Output:
Content-Length:91
Content-Type:application/json
Host:localhost:1234
Origin:http://localhost:1234
Referer:http://localhost:1234/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{"application":"AirFare","from":"2013-10-10T11:47:50.681Z","to":"2013-10-10T11:47:50.681Z"}
Are you using the latest version of AngularJS?
To solve this problem, I follow the Scot Hanselman approach at Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied) article, the code with example is bellow:
class Program
{
static void Main(string[] args)
{
var path = "c:\\temp\\notfound.txt";
try
{
File.Delete(path);
}
catch (UnauthorizedAccessException)
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
attributes &= ~FileAttributes.ReadOnly;
File.SetAttributes(path, attributes);
File.Delete(path);
}
else
{
throw;
}
}
}
}
You can easily determine the file MIME type with JavaScript's FileReader
before uploading it to a server. I agree that we should prefer server-side checking over client-side, but client-side checking is still possible. I'll show you how and provide a working demo at the bottom.
Check that your browser supports both File
and Blob
. All major ones should.
if (window.FileReader && window.Blob) {
// All the File APIs are supported.
} else {
// File and Blob are not supported
}
You can retrieve the File
information from an <input>
element like this (ref):
<input type="file" id="your-files" multiple>
<script>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
// When the control has changed, there are new files
var files = control.files,
for (var i = 0; i < files.length; i++) {
console.log("Filename: " + files[i].name);
console.log("Type: " + files[i].type);
console.log("Size: " + files[i].size + " bytes");
}
}, false);
</script>
Here is a drag-and-drop version of the above (ref):
<div id="your-files"></div>
<script>
var target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
event.preventDefault();
}, false);
target.addEventListener("drop", function(event) {
// Cancel default actions
event.preventDefault();
var files = event.dataTransfer.files,
for (var i = 0; i < files.length; i++) {
console.log("Filename: " + files[i].name);
console.log("Type: " + files[i].type);
console.log("Size: " + files[i].size + " bytes");
}
}, false);
</script>
We can now inspect the files and tease out headers and MIME types.
✘ Quick method
You can naïvely ask Blob for the MIME type of whatever file it represents using this pattern:
var blob = files[i]; // See step 1 above
console.log(blob.type);
For images, MIME types come back like the following:
image/jpeg
image/png
...
Caveat: The MIME type is detected from the file extension and can be fooled or spoofed. One can rename a .jpg
to a .png
and the MIME type will be be reported as image/png
.
✓ Proper header-inspecting method
To get the bonafide MIME type of a client-side file we can go a step further and inspect the first few bytes of the given file to compare against so-called magic numbers. Be warned that it's not entirely straightforward because, for instance, JPEG has a few "magic numbers". This is because the format has evolved since 1991. You might get away with checking only the first two bytes, but I prefer checking at least 4 bytes to reduce false positives.
Example file signatures of JPEG (first 4 bytes):
FF D8 FF E0 (SOI + ADD0)
FF D8 FF E1 (SOI + ADD1)
FF D8 FF E2 (SOI + ADD2)
Here is the essential code to retrieve the file header:
var blob = files[i]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log(header);
// Check the file signature against known types
};
fileReader.readAsArrayBuffer(blob);
You can then determine the real MIME type like so (more file signatures here and here):
switch (header) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
case "ffd8ffe3":
case "ffd8ffe8":
type = "image/jpeg";
break;
default:
type = "unknown"; // Or you can use the blob.type as fallback
break;
}
Accept or reject file uploads as you like based on the MIME types expected.
Here is a working demo for local files and remote files (I had to bypass CORS just for this demo). Open the snippet, run it, and you should see three remote images of different types displayed. At the top you can select a local image or data file, and the file signature and/or MIME type will be displayed.
Notice that even if an image is renamed, its true MIME type can be determined. See below.
Screenshot
// Return the first few bytes of the file as a hex string_x000D_
function getBLOBFileHeader(url, blob, callback) {_x000D_
var fileReader = new FileReader();_x000D_
fileReader.onloadend = function(e) {_x000D_
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);_x000D_
var header = "";_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
header += arr[i].toString(16);_x000D_
}_x000D_
callback(url, header);_x000D_
};_x000D_
fileReader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
function getRemoteFileHeader(url, callback) {_x000D_
var xhr = new XMLHttpRequest();_x000D_
// Bypass CORS for this demo - naughty, Drakes_x000D_
xhr.open('GET', '//cors-anywhere.herokuapp.com/' + url);_x000D_
xhr.responseType = "blob";_x000D_
xhr.onload = function() {_x000D_
callback(url, xhr.response);_x000D_
};_x000D_
xhr.onerror = function() {_x000D_
alert('A network error occurred!');_x000D_
};_x000D_
xhr.send();_x000D_
}_x000D_
_x000D_
function headerCallback(url, headerString) {_x000D_
printHeaderInfo(url, headerString);_x000D_
}_x000D_
_x000D_
function remoteCallback(url, blob) {_x000D_
printImage(blob);_x000D_
getBLOBFileHeader(url, blob, headerCallback);_x000D_
}_x000D_
_x000D_
function printImage(blob) {_x000D_
// Add this image to the document body for proof of GET success_x000D_
var fr = new FileReader();_x000D_
fr.onloadend = function() {_x000D_
$("hr").after($("<img>").attr("src", fr.result))_x000D_
.after($("<div>").text("Blob MIME type: " + blob.type));_x000D_
};_x000D_
fr.readAsDataURL(blob);_x000D_
}_x000D_
_x000D_
// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures_x000D_
function mimeType(headerString) {_x000D_
switch (headerString) {_x000D_
case "89504e47":_x000D_
type = "image/png";_x000D_
break;_x000D_
case "47494638":_x000D_
type = "image/gif";_x000D_
break;_x000D_
case "ffd8ffe0":_x000D_
case "ffd8ffe1":_x000D_
case "ffd8ffe2":_x000D_
type = "image/jpeg";_x000D_
break;_x000D_
default:_x000D_
type = "unknown";_x000D_
break;_x000D_
}_x000D_
return type;_x000D_
}_x000D_
_x000D_
function printHeaderInfo(url, headerString) {_x000D_
$("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))_x000D_
.after($("<div>").text("File header: 0x" + headerString))_x000D_
.after($("<div>").text(url));_x000D_
}_x000D_
_x000D_
/* Demo driver code */_x000D_
_x000D_
var imageURLsArray = ["http://media2.giphy.com/media/8KrhxtEsrdhD2/giphy.gif", "http://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", "http://static.giantbomb.com/uploads/scale_small/0/316/520157-apple_logo_dec07.jpg"];_x000D_
_x000D_
// Check for FileReader support_x000D_
if (window.FileReader && window.Blob) {_x000D_
// Load all the remote images from the urls array_x000D_
for (var i = 0; i < imageURLsArray.length; i++) {_x000D_
getRemoteFileHeader(imageURLsArray[i], remoteCallback);_x000D_
}_x000D_
_x000D_
/* Handle local files */_x000D_
$("input").on('change', function(event) {_x000D_
var file = event.target.files[0];_x000D_
if (file.size >= 2 * 1024 * 1024) {_x000D_
alert("File size must be at most 2MB");_x000D_
return;_x000D_
}_x000D_
remoteCallback(escape(file.name), file);_x000D_
});_x000D_
_x000D_
} else {_x000D_
// File and Blob are not supported_x000D_
$("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );_x000D_
} /* Drakes, 2015 */
_x000D_
img {_x000D_
max-height: 200px_x000D_
}_x000D_
div {_x000D_
height: 26px;_x000D_
font: Arial;_x000D_
font-size: 12pt_x000D_
}_x000D_
form {_x000D_
height: 40px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="file" />_x000D_
<div>Choose an image to see its file signature.</div>_x000D_
</form>_x000D_
<hr/>
_x000D_
To convert it to a single dictionary with some decided keys value, you can use the code below.
data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
ListOfDictAsDict[PrecedingText + str(i)] = data[i]
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
You can do this in a number of ways. You can use databinding (typical initialized after InitializeComponent();)
textBox1.DataBindings.Add(new Binding("Text", yourBindingSource,
"TableName.ColumnName", true, DataSourceUpdateMode.OnPropertyChanged));
or use a DataLayoutControl (if you are going to use textbox for editing, I really recommend spending some time to learn how to use this component.
or in FocusedRowChanged by assigning from one of these methods:
textBox1.Text = gridView1.GetDataRow(e.FocusedRowHandle)["Name"].ToString();
textBox1.Text = gridView1.GetFocusedDataRow()["Name"].ToString();
textBox1.Text = (gridView1.GetFocusedRow() as DataRowView).Row["Name"].ToString();
textBox1.Text = gridView1.GetFocusedRowCellValue("Name").ToString();
if you have numbers in list, you can use map
to apply str
to each element:
print ', '.join(map(str, LIST))
^ map
is C code so it's faster than str(i) for i in LIST
You can use @@trancount
in MSSQL
From the documentation:
Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.
Pass true
as the append
parameter of the constructor:
TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
Any one got the same issue it's related to a conflict between brew and npm Please check this solution https://gist.github.com/DanHerbert/9520689
You don't need a generate bock if you want all the bits of temp
assigned in the same always block.
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
for (integer c=0; c<ROWBITS; c=c+1) begin: test
temp[c] <= 1'b0;
end
end
Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
temp <= '0; // fill with 0
end
end
I used:
TableLayout tablelayout = (TableLayout) view.findViewById(R.id.table);
tablelayout.setColumnShrinkable(1,true);
it worked for me. 1 is the number of column.
I start with the following template, which is derived from numerous printings of Itzik Ben-Gan's routine:
;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
select Number from Tally where Number <= 1000000
The "WHERE N<= 1000000" clause limits the output to 1 to 1 million, and can easily be adjusted to your desired range.
Since this is a WITH clause, it can be worked into an INSERT... SELECT... like so:
-- Sample use: create one million rows
CREATE TABLE dbo.Example (ExampleId int not null)
DECLARE @RowsToCreate int
SET @RowsToCreate = 1000000
-- "Table of numbers" data generator, as per Itzik Ben-Gan (from multiple sources)
;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
INSERT Example (ExampleId)
select Number
from Tally
where Number <= @RowsToCreate
Indexing the table after it's built will be the fastest way to index it.
Oh, and I'd refer to it as a "Tally" table. I think this is a common term, and you can find loads of tricks and examples by Googling it.
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
vector<string> split(string str, string token){
vector<string>result;
while(str.size()){
int index = str.find(token);
if(index!=string::npos){
result.push_back(str.substr(0,index));
str = str.substr(index+token.size());
if(str.size()==0)result.push_back(str);
}else{
result.push_back(str);
str = "";
}
}
return result;
}
split("1,2,3",",") ==> ["1","2","3"]
split("1,2,",",") ==> ["1","2",""]
split("1token2token3","token") ==> ["1","2","3"]
It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.
1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword
Your certificate selfsigncert.pfx will be located @ D:/
Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"