A +1 to accepted answer:
Destination Selection in Installer
If domain (a.k.a destination) selection is desired between user domain and system domain then rather than trying <domains enable_anywhere="true">
use following:
<domains enable_currentUserHome="true" enable_localSystem="true"/>
enable_currentUserHome installs application app under ~/Applications/
and enable_localSystem
allows the application to be installed under /Application
I've tried this in El Capitan 10.11.6 (15G1217) and it seems to be working perfectly fine in 1 dev machine and 2 different VMs I tried.
This is a lightweight solution I've come across -
function E() { // Check collision
S = X - x;
D = Y - y;
F = w + W;
return (S * S + D * D <= F * F)
}
The big and small variables are of two objects, (x coordinate, y coordinate, and w width)
From here.
Using Woodstox, configure the StAX parser to validate against your schema and parse the XML.
If exceptions are caught the XML is not valid, otherwise it is valid:
// create the XSD schema from your schema file
XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
XMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);
// create the XML reader for your XML file
WstxInputFactory inputFactory = new WstxInputFactory();
XMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);
try {
// configure the reader to validate against the schema
xmlReader.validateAgainst(validationSchema);
// parse the XML
while (xmlReader.hasNext()) {
xmlReader.next();
}
// no exceptions, the XML is valid
} catch (XMLStreamException e) {
// exceptions, the XML is not valid
} finally {
xmlReader.close();
}
Note: If you need to validate multiple files, you should try to reuse your XMLInputFactory
and XMLValidationSchema
in order to maximize the performance.
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
Use this
if (sizeof($arr) > 1) {
....
}
Or
if (count($arr) > 1) {
....
}
sizeof()
is an alias for count()
, they work the same.
Edit:
Answering the second part of the question:
The two lines of codes in the question are not alternative methods, they perform different functions. The first checks if the value at $arr['1']
is set, while the second returns the number of elements in the array.
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.
Both use the following JavaScript with jQuery:
$("#commentForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
alert("This is a valid form!");
// form.submit();
}
});
The main differences between the two plugins are the attributes used for each approach.
jQuery Validation
Simply use the following attributes:
Here's the form...
<form id="commentForm">
<label for="form-name">Name (required, at least 2 characters)</label>
<input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
<input type="submit" value="Submit">
</form>
jQuery Validation Unobtrusive
The following data attributes are needed:
Here's the form...
<form id="commentForm">
<label for="form-x-name">Name (required, at least 2 characters)</label>
<input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
<input type="submit" value="Submit">
</form>
Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.
References: - jQuery Validation: https://jqueryvalidation.org/documentation/
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
I'm guessing you did not want to use a breakpoint because it will always break the line. Is that correct? If so how about adding a breakpoint <br />
in your text, then giving it a class like <br class="hidebreak"/>
then using media query right above the size you want it to break to hide the <br />
so it breaks at a specific width but stays inline above that width.
HTML:
<p>
The below line breaks at 766px.
</p>
<p>
This is the line of text<br class="hidebreak"> I want to break.
</p>
CSS:
@media (min-width: 767px) {
br.hidebreak {display:none;}
}
Parsing pingtest.txt for each HOST name and result with batch is difficult because the name and result are on different lines.
It is much easier to test the result (the returned error code) of each PING command directly instead of redirecting to a file. It is also more efficient to enclose the entire construct in parens and redirect the final output just once.
>result.txt (
for /f %%i in (testservers.txt) do ping -n 1 %%i >nul && echo %%i UP||echo %%i DOWN
)
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".
Further from UML standard:
composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).
So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)
Precise semantics of shared aggregation varies by application area and modeler.
I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.
Initially define a function pointer array which takes a void and returns a void.
Assuming that your function is taking a void and returning a void.
typedef void (*func_ptr)(void);
Now you can use this to create function pointer variables of such functions.
Like below:
func_ptr array_of_fun_ptr[3];
Now store the address of your functions in the three variables.
array_of_fun_ptr[0]= &A;
array_of_fun_ptr[1]= &B;
array_of_fun_ptr[2]= &C;
Now you can call these functions using function pointers as below:
some_a=(*(array_of_fun_ptr[0]))();
some_b=(*(array_of_fun_ptr[1]))();
some_c=(*(array_of_fun_ptr[2]))();
I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.
The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.
Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.
@Html.DropDownList("ddl",Model.Select(item => new SelectListItem
{
Value = item.RecordID.ToString(),
Text = item.Name.ToString(),
Selected = "select" == item.RecordID.ToString()
}))
This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.
To parallelize your example, you'd need to define your functions with the @ray.remote decorator
, and then invoke them with .remote
.
import ray
ray.init()
# Define functions you want to execute in parallel using
# the ray.remote decorator.
@ray.remote
def func1():
print("Working")
@ray.remote
def func2():
print("Working")
# Execute func1 and func2 in parallel.
ray.get([func1.remote(), func2.remote()])
If func1()
and func2()
return results, you need to rewrite the above code a bit, by replacing ray.get([func1.remote(), func2.remote()])
with:
ret_id1 = func1.remote()
ret_id2 = func1.remote()
ret1, ret2 = ray.get([ret_id1, ret_id2])
There are a number of advantages of using Ray over the multiprocessing module or using multithreading. In particular, the same code will run on a single machine as well as on a cluster of machines.
For more advantages of Ray see this related post.
Seems question is not about strings equality, but of sets equality. You can compare them this way only by splitting strings and converting them to sets:
s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' '))
set2 = set(s2.split(' '))
print set1 == set2
Result will be
True
I found two reasons why this error might occur.
One. The Window flags are set already set inside super.onCreate(savedInstanceState);
in which case you may want to use the following order of commands:
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
Two. You have the Back/Up button inside the TitleBar, meaning that the current activity is a hierarchical child of another activity, in which case you might want to comment out or remove this line of code from inside the onCreate
method.
getActionBar().setDisplayHomeAsUpEnabled(true);
You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.
function form($scope){_x000D_
$scope.onSubmit = function(){_x000D_
alert("form submitted");_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
<input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
What if you hooked the window resize event:
$(window).resize(function()
{
chart.setSize(
$(document).width(),
$(document).height()/2,
false
);
});
See example fiddle here.
Highcharts API Reference : setSize().
You'll have to use the ChannelFactory class.
Here's an example:
var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
IMyService client = null;
try
{
client = myChannelFactory.CreateChannel();
client.MyServiceOperation();
((ICommunicationObject)client).Close();
myChannelFactory.Close();
}
catch
{
(client as ICommunicationObject)?.Abort();
}
}
Related resources:
Check on your index.php
, find "... charset=iso-8859-1
" and replace it with "... charset=utf-8
".
Maybe it'll work.
Type related errors can be avoided by imposing a schema as follows:
note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").
import pyspark
from pyspark.sql import SparkSession
import pandas as pd
spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()
pdDF = pd.read_csv("test.csv")
contents of the pandas data frame:
col1 col2 col3 col4 col5 col6 col7 col8 ...
0 10000001 1 0 1 12:35 OK 10002 1 ...
1 10000001 2 0 1 12:36 OK 10002 1 ...
2 10000002 1 0 4 12:19 PA 10003 1 ...
Next, create the schema:
from pyspark.sql.types import *
mySchema = StructType([ StructField("col1", LongType(), True)\
,StructField("col2", IntegerType(), True)\
,StructField("col3", IntegerType(), True)\
,StructField("col4", IntegerType(), True)\
,StructField("col5", StringType(), True)\
,StructField("col6", StringType(), True)\
,StructField("col7", IntegerType(), True)\
,StructField("col8", IntegerType(), True)\
,StructField("col9", IntegerType(), True)\
,StructField("col10", IntegerType(), True)\
,StructField("col11", StringType(), True)\
,StructField("col12", StringType(), True)\
,StructField("col13", IntegerType(), True)\
,StructField("col14", IntegerType(), True)\
,StructField("col15", IntegerType(), True)\
,StructField("col16", IntegerType(), True)\
,StructField("col17", IntegerType(), True)\
,StructField("col18", IntegerType(), True)\
,StructField("col19", IntegerType(), True)\
,StructField("col20", IntegerType(), True)\
,StructField("col21", IntegerType(), True)\
,StructField("col22", IntegerType(), True)\
,StructField("col23", IntegerType(), True)\
,StructField("col24", IntegerType(), True)\
,StructField("col25", IntegerType(), True)])
Note: True
(implies nullable allowed)
create the pyspark dataframe:
df = spark.createDataFrame(pdDF,schema=mySchema)
confirm the pandas data frame is now a pyspark data frame:
type(df)
output:
pyspark.sql.dataframe.DataFrame
Aside:
To address Kate's comment below - to impose a general (String) schema you can do the following:
df=spark.createDataFrame(pdDF.astype(str))
Just create and save a page token in global variable with window.nextPageToken
. Send this to API server everytime you make a request and have it return the next one with response and you can easily keep track of last token. The below is an example how you can move forward and backward from search results. The key is the offset you send to API based on the nextPageToken that you have saved:
function getPrev() {
var offset = Number(window.nextPageToken) - limit * 2;
if (offset < 0) {
offset = 0;
}
window.nextPageToken = offset;
if (canSubmit(searchForm, offset)) {
searchForm.submit();
}
}
function getNext() {
var offset = Number(window.nextPageToken);
window.nextPageToken = offset;
if (canSubmit(searchForm, offset)) {
searchForm.submit();
}
}
My synopsis of rfc2397 is:
Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64,
" this is similar to the prefixing done in the parenthesis of url()
definition in CSS or in the quoted value of the src
attribute of the img
tag in [X]HTML. You can test the data url in firefox by putting the data:image/...
line into the URL field and pressing enter, it should show your image.
For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.
base64
command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
A note on mime-types:
I would prefer you use one of image/png
image/jpeg
or image/gif
as I can't find the popular image/x-icon
. Should that be image/vnd.microsoft.icon
?
Also the other formats are much shorter.
compare 265 bytes vs 1150 bytes:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=
data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
Heres the code that creates a Dialog which allows the user of your application to change the Look And Feel based on the user's systems. Alternatively, if you can store the wanted Look And Feel's on your application, then they could be "portable", which is the desired result.
public void changeLookAndFeel() {
List<String> lookAndFeelsDisplay = new ArrayList<>();
List<String> lookAndFeelsRealNames = new ArrayList<>();
for (LookAndFeelInfo each : UIManager.getInstalledLookAndFeels()) {
lookAndFeelsDisplay.add(each.getName());
lookAndFeelsRealNames.add(each.getClassName());
}
String changeLook = (String) JOptionPane.showInputDialog(this, "Choose Look and Feel Here:", "Select Look and Feel", JOptionPane.QUESTION_MESSAGE, null, lookAndFeelsDisplay.toArray(), null);
if (changeLook != null) {
for (int i = 0; i < lookAndFeelsDisplay.size(); i++) {
if (changeLook.equals(lookAndFeelsDisplay.get(i))) {
try {
UIManager.setLookAndFeel(lookAndFeelsRealNames.get(i));
break;
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
err.println(ex);
ex.printStackTrace(System.err);
}
}
}
}
}
If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).
Use this single sql statement which is safe no need of commit/rollback with multiple statements.
INSERT Table2 (
username,password
) SELECT username,password
FROM (
DELETE Table1
OUTPUT
DELETED.username,
DELETED.password
WHERE username = 'X' and password = 'X'
) AS RowsToMove ;
Works on SQL server make appropriate changes for MySql
In case the top answers haven't worked for you, your issue may be that you have multiple dependencies that depend on the same library.
Here are some debugging tips. In this sample code, com.google.code.findbugs:jsr305:3.0.0
is the offending library.
Always clean and rebuild every time you modify to check your solution!
Build with the --stacktrace
flag on for more detail. It will complain about a class, Google that class to find the library. Here's how you can set up Android studio to always run gradle with the --stacktrace
flag.
Take a glance at the Gradle Console in Android Studio View > Tool Windows > Gradle Console
after a build
Check for repeated dependences by running ./gradlew -q app:dependencies
. You can re-run this each time you modify the your build.gradle.
In build.gradle,
android {
...
configurations.all {
resolutionStrategy {
// Force a particular version of the library
// across all dependencies that have that dependency
force 'com.google.code.findbugs:jsr305:3.0.0'
}
}
}
In build.gradle,
dependencies {
...
implementation('com.google.auth:google-auth-library-oauth2-http:0.6.0') {
// Exclude the library for this particular import
exclude group: 'com.google.code.findbugs'
}
}
In build.gradle,
android {
...
configurations.all {
resolutionStrategy {
// Completely exclude the library. Works for transitive
// dependencies.
exclude group: 'com.google.code.findbugs'
}
}
}
If some of your dependencies are in jar files, open up the jar files and see if there are any conflicting class names. If they are, you will probably have to re-build the jars with new class names or look into shading.
Some more background reading:
FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.
Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.
You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.
public static class HelperExtensions
{
//Convert Image to byte[] array:
public static byte[] ToByteArray(this Image imageIn)
{
var ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
//Convert byte[] array to Image:
public static Image ToImage(this byte[] byteArrayIn)
{
var ms = new MemoryStream(byteArrayIn);
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
You can avoid declaration of global variables by adding them directly to the global object:
(function(global) {
...
global.varName = someValue;
...
}(this));
A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.
You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.
When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}
.
@click
is just shorthand for v-on:click
directive so the same rules apply.
In your case, simply use @click="addToCount(item.contactID)"
I wrote this answer about four years ago and my opinion hasn't changed. But since then there have been significant developments on the micro-services front. I added micro-services specific notes at the end...
I'll weigh in against the idea, with real-world experience to back up my vote.
I was brought on to a large application that had five contexts for a single database. In the end, we ended up removing all of the contexts except for one - reverting back to a single context.
At first the idea of multiple contexts seems like a good idea. We can separate our data access into domains and provide several clean lightweight contexts. Sounds like DDD, right? This would simplify our data access. Another argument is for performance in that we only access the context that we need.
But in practice, as our application grew, many of our tables shared relationships across our various contexts. For example, queries to table A in context 1 also required joining table B in context 2.
This left us with a couple poor choices. We could duplicate the tables in the various contexts. We tried this. This created several mapping problems including an EF constraint that requires each entity to have a unique name. So we ended up with entities named Person1 and Person2 in the different contexts. One could argue this was poor design on our part, but despite our best efforts, this is how our application actually grew in the real world.
We also tried querying both contexts to get the data we needed. For example, our business logic would query half of what it needed from context 1 and the other half from context 2. This had some major issues. Instead of performing one query against a single context, we had to perform multiple queries across different contexts. This has a real performance penalty.
In the end, the good news is that it was easy to strip out the multiple contexts. The context is intended to be a lightweight object. So I don't think performance is a good argument for multiple contexts. In almost all cases, I believe a single context is simpler, less complex, and will likely perform better, and you won't have to implement a bunch of work-arounds to get it to work.
I thought of one situation where multiple contexts could be useful. A separate context could be used to fix a physical issue with the database in which it actually contains more than one domain. Ideally, a context would be one-to-one to a domain, which would be one-to-one to a database. In other words, if a set of tables are in no way related to the other tables in a given database, they should probably be pulled out into a separate database. I realize this isn't always practical. But if a set of tables are so different that you would feel comfortable separating them into a separate database (but you choose not to) then I could see the case for using a separate context, but only because there are actually two separate domains.
Regarding micro-services, one single context still makes sense. However, for micro-services, each service would have its own context which includes only the database tables relevant to that service. In other words, if service x accesses tables 1 and 2, and service y accesses tables 3 and 4, each service would have its own unique context which includes tables specific to that service.
I'm interested in your thoughts.
That method will not work. The <title>
only supports plain text. You will need to create an .ico
image with the filename of favicon.ico
and save it into the root folder of your site (where your default page is).
Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head>
section of your HTML and reference your icon:
<link rel="shortcut icon" href="your_image_path_and_name.ico" />
You can use Photoshop (with a plug in) or GIMP (free) to create an .ico
file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).
Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.
Update 2: You can also use .png
images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico
files.
Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.
The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.
Character Devices
Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).
TTY
/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty
, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty
, your subsequent input gets duplicated (until you press Ctrl-C).
/dev/tty
doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0
is normally your serial port)
This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :
/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).
Here is the man page: http://linux.die.net/man/4/tty
To read the contents of a file into a String from the classpath
, you can use this:
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
Note:
IOUtils
is part of Commons IO
.
Call it like this:
String fileContents = resourceToString("ImOnTheClasspath.txt");
Just for completeness, there is also the LINQ/Lambda way:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
In this example, nothing really. The exact
param comes into play when you have multiple paths that have similar names:
For example, imagine we had a Users
component that displayed a list of users. We also have a CreateUser
component that is used to create users. The url for CreateUsers
should be nested under Users
. So our setup could look something like this:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Now the problem here, when we go to http://app.com/users
the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users
route first and then return it. All good.
But, if we went to http://app.com/users/create
, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users
partially matches /users/create
, so it would incorrectly return the Users
route again!
The exact
param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.
So in this case, we should add exact
to our Users
route so that it will only match on /users
:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
As the whole thing is mixing up let's look at it function and code to simulate what it means consicely
The only way to get a row is via primary key
getRow(pk: PrimaryKey): Row
Primary key data structure can be this:
// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)
// and in thids case
getRow(somePartitionKey): Row
However you can decide your primary key is partition key + sort key in this case:
// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)
getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]
So the bottom line:
Decided that your primary key is partition key only? get single row by partition key.
Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)
In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key
Building blocks are:
Think of Item as a row and of KV Attribute as cells in that row.
You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).
More visually as its complex, the way I see it:
+----------------------------------------------------------------------------------+
|Table |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
| |
+----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey |
| +--------------------------+|
| +---------------+ |getByPK => getBy(1 ||
| +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
| +->|Composite |-+ +---------------+ |of rangeKeys) ||
| | +-----------+ +--------------------------+|
|+-----------+ | |
||PrimaryKey |-+ |
|+-----------+ | +--------------------------+|
| | +-----------+ +---------------+ |getByPK => get by specific||
| +->|HashType |-->|get one item |--->|hashKey ||
| +-----------+ +---------------+ | ||
| +--------------------------+|
+----------------------------------------------------------------------------------+
So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.
If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.
Note: I did not refer to secondary indexes.
Don't know of a framework method but you could write a quick helper to do it for you.
public static void Populate<T>(this T[] arr, T value ) {
for ( int i = 0; i < arr.Length;i++ ) {
arr[i] = value;
}
}
There is a collector joining
in the API.
It's a static method in Collectors
.
list.stream().map(Object::toString).collect(Collectors.joining(","))
Not perfect because of the necessary call of toString
, but works. Different delimiters are possible.
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Issue is with remote server, can you login to the remote server and check if "scp" works
probable causes: - scp is not in path - openssh client not installed correctly
for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/
Parse the two dates firstDate
and secondDate
using SimpleDateFormat
.
firstDate.after(secondDate);
firstDate.before(secondDate);
The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.
It works pretty good for testing.
Now has string enums so your code just works:
enum E {
hello = "hello",
world = "world"
};
Since TypeScript 1.8 you can use string literal types to provide a reliable and safe experience for named string values (which is partially what enums are used for).
type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay
foo = "asdf"; // Error!
More : https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
Enums in TypeScript are number based.
You can use a class with static members though:
class E
{
static hello = "hello";
static world = "world";
}
You could go plain as well:
var E = {
hello: "hello",
world: "world"
}
Update:
Based on the requirement to be able to do something like var test:E = E.hello;
the following satisfies this:
class E
{
// boilerplate
constructor(public value:string){
}
toString(){
return this.value;
}
// values
static hello = new E("hello");
static world = new E("world");
}
// Sample usage:
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;
console.log("First value is: "+ first);
console.log(first===third);
I use this command:
netstat -tulpn | grep LISTEN
You can have a clean output that shows process id and ports that's listening on
As of today you can throttle your connection natively in Google Chrome Canary 46.0.2489.0
. Simply open up Dev Tools and head over to the Network tab:
Also make sure your Workspace Settings aren't overriding your User Settings. The UI doesn't make it very obvious which settings you're editing and "File > Preferences > Settings" defaults to User Settings even though Workspace Settings trump User Settings.
You can also edit Workspace settings directly: /.vscode/settings.json
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
In Lua 5.2 the best workaround is to use goto:
-- prints odd numbers in [|1,10|]
for i=1,10 do
if i % 2 == 0 then goto continue end
print(i)
::continue::
end
This is supported in LuaJIT since version 2.0.1
Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.
>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa
Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.
>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa
same from above example - if you are just looking for json (not an array of object) just use
function getJsonDetails() {
item = {}
item ["token1"] = token1val;
item ["token2"] = token1val;
return item;
}
console.log(JSON.stringify(getJsonDetails()))
this output ll print as (a valid json)
{
"token1":"samplevalue1",
"token2":"samplevalue2"
}
Use the ampersand just like you would from the shell.
#!/usr/bin/bash
function_to_fork() {
...
}
function_to_fork &
# ... execution continues in parent process ...
It's all in your error message - seems like unclean shutdown was detected. See http://docs.mongodb.org/manual/tutorial/recover-data-following-unexpected-shutdown/ for detailed information.
In my expirience, usually it helps to run mongod.exe
with --repair
option ro repair DB.
Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::
.
You can use for it the is
operator. You can then check if object is specific type by writing:
if (myObject is string)
{
DoSomething()
}
You may require to install Language Packs: 3.2
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded
formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data
. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
SRCS=$(wildcard *.c)
OBJS=$(SRCS:.c=.o)
all: $(OBJS)
I am using Cent OS 6.6 with Apache and for me error log files are in
/usr/local/apache/log
There is plenty of libraries out there and I'm using this one: https://github.com/nerde/rest-resource. This was created by me, and, as you can see in the documentation, it's way cleaner and simpler than the other ones. It's not focused on Android, but I'm using in it and it's working pretty well.
It supports HTTP Basic Auth. It does the dirty job of serializing and deserializing JSON objects. You will like it, specially if your API is Rails like.
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
This will print each character in text
text = raw_input("Give some input: ")
for i in range(0,len(text)):
print(text[i])
To avoid this error you could either:
You will find instructions on signing third-party assemblies in .NET-fu: Signing an Unsigned Assembly (Without Delay Signing).
The basic principle to sign a thirp-party is to
Disassemble the assembly using ildasm.exe
and save the intermediate language (IL):
ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll
Rebuild and sign the assembly:
ilasm /dll /key=myKey.snk thirdPartyLib.il
The above steps work fine unless your third-party assembly (A.dll) references another library (B.dll) which also has to be signed. You can disassemble, rebuild and sign both A.dll and B.dll using the commands above, but at runtime, loading of B.dll will fail because A.dll was originally built with a reference to the unsigned version of B.dll.
The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling
sn -Tp B.dll
which will give you the following output:
Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.33440
Copyright (c) Microsoft Corporation. All rights reserved.
Public key (hash algorithm: sha1):
002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3
b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb
4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758
cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c
78effe92
Public key token is a8a7ed7203d87bc9
The last line contains the public key token. You then have to search the IL of A.dll for the reference to B.dll and add the token as follows:
.assembly extern /*23000003*/ MyAssemblyName
{
.publickeytoken = (A8 A7 ED 72 03 D8 7B C9 )
.ver 10:0:0:0
}
How about just using the built-in types like this:
config = {
"mysql": {
"user": "root",
"pass": "secret",
"tables": {
"users": "tb_users"
}
# etc
}
}
You'd access the values as follows:
config["mysql"]["tables"]["users"]
If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:
mysql:
- user: root
- pass: secret
- tables:
- users: tb_users
and use a library like PyYAML to conventiently parse and access the config file
Lambda Expression result
var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();
//start use session
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
}
else {
echo "Invalid user and password";
header("Locatin:form.php");
}
if(isset($_SESSION['user']))
{
//your home page code here
exit;
}
Creating an IPA is done along the same way as creating an .xcarchive: Product -> Archive. After the Archive operation completes, go to the Organizer, select your archive, select Share and in the "Select the content and options for sharing:" pane set Contents to "iOS App Store Package (.ipa) and Identity to iPhone Distribution (which should match your ad hoc/app store provisioning profile for the project).
Chances are the "iOS App Store Package (.ipa)" option may be disabled. This happens when your build produces more than a single target: say, an app and a library. All of them end up in the build products folder and Xcode gets naïvely confused about how to package them both into an .ipa file, so it merely disables the option.
A way to solve this is as follows: go through build settings for each of the targets, except the application target, and set Skip Install flag to YES. Then do the Product -> Archive tango once again and go to the Organizer to select your new archive. Now, when clicking on the Share button, the .ipa option should be enabled.
I hope this helps.
var myString = 'sample String'; var length = myString.length ;
first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above
public static void main(String[] args){
String string = "elamparuthi, elam, elamparuthi";
String[] s = string.replace(" ", "").split(",");
String[] op;
String ops = "";
for(int i=0; i<=s.length-1; i++){
if(!ops.contains(s[i]+"")){
if(ops != "")ops+=", ";
ops+=s[i];
}
}
System.out.println(ops);
}
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
Try below code segment, I've tried it myself before :
#your-div {
background: url("your-image-link") no-repeat;
background-size: cover;
background-clip: border-box;
}
The other answers are totally fine:
However, if you still want a typed variant, there is a built-in solution since Python 3.5.
Generic classes:
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
def empty(self) -> bool:
return not self.items
# Construct an empty Stack[int] instance
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x') # Type error
Generic functions:
from typing import TypeVar, Sequence
T = TypeVar('T') # Declare type variable
def first(seq: Sequence[T]) -> T:
return seq[0]
def last(seq: Sequence[T]) -> T:
return seq[-1]
n = first([1, 2, 3]) # n has type int.
Reference: mypy documentation about generics.
public static DataTable ConvertExcelToDataTable(string filePath, bool isXlsx = false)
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
//open file and returns as Stream
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true
}
};
var dataSet = reader.AsDataSet(conf);
// Now you can get data from each sheet by its index or its "name"
var dataTable = dataSet.Tables[0];
Console.WriteLine("Total no of rows " + dataTable.Rows.Count);
Console.WriteLine("Total no of Columns " + dataTable.Columns.Count);
return dataTable;
}
}
}
If the object is actually a Boolean
instance, then just cast it:
boolean di = (Boolean) someObject;
The explicit cast will do the conversion to Boolean
, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:
boolean di = ((Boolean) someObject).booleanValue();
If someObject
doesn't refer to a Boolean value though, what do you want the code to do?
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
If you have a small number of values to auto complete, you can simply add them in xaml. Typing will invoke auto-complete, plus you have dropdowns too.
<ComboBox Text="{Binding CheckSeconds, UpdateSourceTrigger=PropertyChanged}"
IsEditable="True">
<ComboBoxItem Content="60"/>
<ComboBoxItem Content="120"/>
<ComboBoxItem Content="180"/>
<ComboBoxItem Content="300"/>
<ComboBoxItem Content="900"/>
</ComboBox>
Maybe powershell -Command "Get-AppLockerFileInformation....."
Take a look at powershell /?
If the contents of the list are primitive data types, you can use a comprehension
new_list = [i for i in old_list]
You can nest it for multidimensional lists like:
new_grid = [[i for i in row] for row in grid]
This actually removes the contents from the list, but doesn't replace the old label with a new empty list:
del lst[:]
Here's an example:
lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)
For the sake of completeness, the slice assignment has the same effect:
lst[:] = []
It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).
Note that doing lst = []
does not empty the list, just creates a new object and binds it to the variable lst
, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']
It works fine for me. Make sure to set the random method.
The accepted answer from Paul is great. I've made a small extension to this which is very useful if you have an multidimensional array like this (which is quite common):
Array
(
[0] => Array
(
[a] => "a"
[b] => "b"
)
[1] => Array
(
[a] => "a2"
[b] => "b2"
)
[2] => Array
(
[a] => "a3"
[b] => "b3"
)
[3] => Array
(
[a] => "a4"
[b] => "b4"
)
[4] => Array
(
[a] => "a5"
[b] => "b5"
)
)
So I just took Paul's function from above:
/**
* Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
* Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
*/
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields as $field ) {
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}
And added this:
function a2c($array, $glue = "\n")
{
$ret = [];
foreach ($array as $item) {
$ret[] = arrayToCsv($item);
}
return implode($glue, $ret);
}
So you can just call:
$csv = a2c($array);
If you want a special line ending you can use the optional parameter "glue" for this.
struct Bool {
int true;
int false;
}
int main() {
/* bool is a variable of data type – bool*/
struct Bool bool;
/*below I’m accessing struct members through variable –bool*/
bool = {1,0};
print("Student Name is: %s", bool.true);
return 0;
}
This is because .
is a reserved character in regular expression, representing any character.
Instead, we should use the following statement:
String extensionRemoved = filename.split("\\.")[0];
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Set data to this:
data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
Still you can't declare any classes like in another programming languages. But you can create as many class variables. But problem is scope of class object. So According to me, Best way OOP Programming in ES6 Javascript:-
class foo{
constructor(){
//decalre your all variables
this.MY_CONST = 3.14;
this.x = 5;
this.y = 7;
// or call another method to declare more variables outside from constructor.
// now create method level object reference and public level property
this.MySelf = this;
// you can also use var modifier rather than property but that is not working good
let self = this.MySelf;
//code .........
}
set MySelf(v){
this.mySelf = v;
}
get MySelf(v){
return this.mySelf;
}
myMethod(cd){
// now use as object reference it in any method of class
let self = this.MySelf;
// now use self as object reference in code
}
}
Asking about "a class" in the question title, the answer is getElementsByClassName
:
var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
for (var i = 0; i < hrefs.length; i++) {
hrefs.item(i).addEventListener('click', function(e){
e.preventDefault(); /*use if you want to prevent the original link following action*/
alert('hohoho');
});
}
#! /bin/bash
if ((2==$#)); then
a=$1
b=$2
alog=$(echo $a | tr '/' '-').log
blog=$(echo $b | tr '/' '-').log
git log --oneline $a > $alog
git log --oneline $b > $blog
diff $alog $blog
fi
Contributing this because it allows a and b logs to be diff'ed visually, side by side, if you have a visual diff tool. Replace diff command at end with command to start visual diff tool.
You should use window variable - window.referrer. This variable contains the last page the user visited if they got to the current page by clicking a link For example:
function goBack() {
if(document.referrer) {
window.location.href = document.referrer;
return;
}
window.location.pathname = '/';
}
This code redirect user to previous page if this is exist and redirect user to homepage if there isn't previous url
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
You need to swap all the back slashes to forward slashes so change
docker -v C:\my\folder:/mountlocation ...
to
docker -v C:/my/folder:/mountlocation ...
I normally call docker from a cmd script where I want the folder to mount to be relative to the script i'm calling so in that script I do this...
SETLOCAL
REM capture the path to this file so we can call on relative scrips
REM without having to be in this dir to do it.
REM capture the path to $0 ie this script
set mypath=%~dp0
REM strip last char
set PREFIXPATH=%mypath:~0,-1%
echo "PREFIXPATH=%PREFIXPATH%"
mkdir -p %PREFIXPATH%\my\folder\to\mount
REM swap \ for / in the path
REM because docker likes it that way in volume mounting
set PPATH=%PREFIXPATH:\=/%
echo "PPATH=%PPATH%"
REM pass all args to this script to the docker command line with %*
docker run --name mycontainername --rm -v %PPATH%/my/folder/to/mount:/some/mountpoint myimage %*
ENDLOCAL
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
If after calling "csrutil disabled" still your command does not work, try with "sudo" in terminal, for example:
sudo mv geckodriver /usr/local/bin
And it should work.
To find out who's making inotify instances, try this command (source):
for foo in /proc/*/fd/*; do readlink -f $foo; done | grep inotify | sort | uniq -c | sort -nr
Mine looked like this:
25 /proc/2857/fd/anon_inode:inotify
9 /proc/2880/fd/anon_inode:inotify
4 /proc/1375/fd/anon_inode:inotify
3 /proc/1851/fd/anon_inode:inotify
2 /proc/2611/fd/anon_inode:inotify
2 /proc/2414/fd/anon_inode:inotify
1 /proc/2992/fd/anon_inode:inotify
Using ps -p 2857
, I was able to identify process 2857 as sublime_text
. Only after closing all sublime windows was I able to run my node script.
You need to give the body
and the html
a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.
Updated fiddle: http://jsfiddle.net/j8bsS/5/
The where
statement gets executed before the order by
. So, your desired query is saying "take the first row and then order it by t_stamp
desc". And that is not what you intend.
The subquery method is the proper method for doing this in Oracle.
If you want a version that works in both servers, you can use:
select ril.*
from (select ril.*, row_number() over (order by t_stamp desc) as seqnum
from raceway_input_labo ril
) ril
where seqnum = 1
The outer *
will return "1" in the last column. You would need to list the columns individually to avoid this.
Import library like:
import CoreLocation
set Delegate:
CLLocationManagerDelegate
Take variable like:
var locationManager:CLLocationManager!
On viewDidLoad() write this pretty code:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
Write CLLocation delegate methods:
//MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation :CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
self.labelLat.text = "\(userLocation.coordinate.latitude)"
self.labelLongi.text = "\(userLocation.coordinate.longitude)"
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
if (error != nil){
print("error in reverseGeocode")
}
let placemark = placemarks! as [CLPlacemark]
if placemark.count>0{
let placemark = placemarks![0]
print(placemark.locality!)
print(placemark.administrativeArea!)
print(placemark.country!)
self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
Now set permission for access the location, so add these key value into your info.plist file
<key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
100% working without any issue. TESTED
Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff') format('woff'), /* Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.
Also , modern browsers are shifting towards .woff font , so you can probably do this too : :
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}
Read more here : http://css-tricks.com/snippets/css/using-font-face/
Look for browser support : Can I Use fontface
Define the url you want to redirect in $url
Then just use
return Redirect::away($url);
If you want to redirect inside your views use
return Redirect::to($url);
Read more about Redirect here
Here is the simple example
return Redirect::to('http://www.google.com');
As the Questioner wants to return in the same page
$triggersms = file_get_contents('http://www.cloud.smsindiahub.in/vendorsms/pushsms.aspx?user=efg&password=abcd&msisdn=9197xxx2&sid=MYID&msg=Hello');
return $triggersms;
Most compilers I've used will at least warn on the if
assignment without further syntax sugar, so I don't buy that argument. That said, I've used both professionally and have no preference for either. The == NULL
is definitely clearer though in my opinion.
Without dropdown ID:
$("#SelectedCountryId").change(function () {
$('option:selected', $(this)).text();
}
You can use OLD
and NEW
in the trigger to access those values which had changed in that trigger. Mysql Ref
Using React Hooks and the useRef
hook.
import React, { useRef } from 'react';
const MyComponent = () => {
const myInput = useRef(null);
const clickElement = () => {
// To simulate a user focusing an input you should use the
// built in .focus() method.
myInput.current?.focus();
// To simulate a click on a button you can use the .click()
// method.
// myInput.current?.click();
}
return (
<div>
<button onClick={clickElement}>
Trigger click inside input
</button>
<input ref={myInput} />
</div>
);
}
Combining all the approaches we can do something like this:
const checkEmpty = document.querySelector('#checkIt');_x000D_
checkEmpty.addEventListener('input', function () {_x000D_
if (checkEmpty.value && // if exist AND_x000D_
checkEmpty.value.length > 0 && // if value have one charecter at least_x000D_
checkEmpty.value.trim().length > 0 // if value is not just spaces_x000D_
) _x000D_
{ console.log('value is: '+checkEmpty.value);}_x000D_
else {console.log('No value'); _x000D_
}_x000D_
});
_x000D_
<input type="text" id="checkIt" required />
_x000D_
Note that if you truly want to check values you should do that on the server, but this is out of the scope for this question.
Found the best way to do it for a server which does not support pkill
kill -9 $(ps ax | grep My_pattern| fgrep -v grep | awk '{ print $1 }')
You do not have to loop.
For Windows 7 macros are stored at C:\Users\
Username
\AppData\Roaming\Notepad++\shortcuts.xml
.
This is what I used for checking if any checkboxes in a list of checkboxes had changed:
$('input[type="checkbox"]').change(function(){
var itemName = $('select option:selected').text();
//Do something.
});
As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
void foo(char* str);
foo("hello");
However, if you want to keep your code warning-free as well then just make respective change in your code:
void foo(char* str);
foo((char *)"hello");
That is, simply cast the string
constant to (char *)
.
You should have sdiff
for side-by-side merge of file differences. Take a read of man sdiff
for the full story.
Ignore me. I'm sorry everyone. I'd mistyped the url of the script. Thanks to Simon Ainley for the prod in the right direction.
Sorry again. Thanks.
Inside your Stack, you should wrap your background
widget in a Positioned.fill.
return new Stack(
children: <Widget>[
new Positioned.fill(
child: background,
),
foreground,
],
);
Use volume API
docker volume create --name hello
docker run -d -v hello:/container/path/for/volume container_image my_command
This means that the data-only container pattern must be abandoned in favour of the new volumes.
Actually the volume API is only a better way to achieve what was the data-container pattern.
If you create a container with a -v volume_name:/container/fs/path
Docker will automatically create a named volume for you that can:
docker volume ls
docker volume inspect volume_name
--volumes-from
connectionThe new volume API adds a useful command that lets you identify dangling volumes:
docker volume ls -f dangling=true
And then remove it through its name:
docker volume rm <volume name>
As @mpugach underlines in the comments, you can get rid of all the dangling volumes with a nice one-liner:
docker volume rm $(docker volume ls -f dangling=true -q)
# Or using 1.13.x
docker volume prune
The approach that seems to work best for production is to use a data only container.
The data only container is run on a barebones image and actually does nothing except exposing a data volume.
Then you can run any other container to have access to the data container volumes:
docker run --volumes-from data-container some-other-container command-to-execute
In this blog post there is a good description of the so-called container as volume pattern which clarifies the main point of having data only containers.
Docker documentation has now the DEFINITIVE description of the container as volume/s pattern.
Following is the backup/restore procedure for Docker 1.8.x and below.
BACKUP:
sudo docker run --rm --volumes-from DATA -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data
RESTORE:
# Create a new data container
$ sudo docker run -v /data -name DATA2 busybox true
# untar the backup files into the new container?s data volume
$ sudo docker run --rm --volumes-from DATA2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar
data/
data/sven.txt
# Compare to the original container
$ sudo docker run --rm --volumes-from DATA -v `pwd`:/backup busybox ls /data
sven.txt
Here is a nice article from the excellent Brian Goff explaining why it is good to use the same image for a container and a data container.
As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.
It has been proposed to assign the global to window
directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!
For now, I would recommend something like this to support proper global management for all run-time environments:
/**
* Exports the given object into the global context.
*/
var exportGlobal = function(name, object) {
if (typeof(global) !== "undefined") {
// Node.js
global[name] = object;
}
else if (typeof(window) !== "undefined") {
// JS with GUI (usually browser)
window[name] = object;
}
else {
throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
}
};
// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);
// create a new global namespace
exportGlobal("someothernamespace", {});
It's a bit more typing, but it makes your global variable management future-proof.
Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.
I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.
Within the dplyr world, try:
select(iris,contains("Sepal"))
See the Selection section in ?select
for numerous other helpers like starts_with
, ends_with
, etc.
The following also can be tried:
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
or use the other setting options in the DataGridViewAutoSizeColumnsMode Enum
Tie::File
is what you need:
Synopsis
# This file documents Tie::File version 0.98 use Tie::File; tie @array, 'Tie::File', 'filename' or die ...; $array[13] = 'blah'; # line 13 of the file is now 'blah' print $array[42]; # display line 42 of the file $n_recs = @array; # how many records are in the file? $#array -= 2; # chop two records off the end for (@array) { s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file } # These are just like regular push, pop, unshift, shift, and splice # Except that they modify the file in the way you would expect push @array, new recs...; my $r1 = pop @array; unshift @array, new recs...; my $r2 = shift @array; @old_recs = splice @array, 3, 7, new recs...; untie @array; # all finished
If you want to apply some condition on form submit then you can use this method
<form onsubmit="return checkEmpData();" method="post" action="process.html">
<input type="text" border="0" name="submit" />
<button value="submit">submit</button>
</form>
One thing always keep in mind that method and action attribute write after onsubmit attributes
javascript code
function checkEmpData()
{
var a = 0;
if(a != 0)
{
return confirm("Do you want to generate attendance?");
}
else
{
alert('Please Select Employee First');
return false;
}
}
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
Undo a merge or pull inside a dirty working tree
$ git pull (1) Auto-merging nitfol Merge made by recursive. nitfol | 20 +++++---- ... $ git reset --merge ORIG_HEAD (2)
Even if you may have local modifications in your working tree, you can safely say
git pull
when you know that the change in the other branch does not overlap with them.After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running
git reset --hard ORIG_HEAD
will let you go back to where you were, but it will discard your local changes, which you do not want.git reset --merge
keeps your local changes.
You can try this
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);
Ok, Denizens. So I have accepted the command line length limits as gospel for quite some time. So, what to do with one's assumptions? Naturally- check them.
I have a Fedora 22 machine at my disposal (meaning: Linux with bash4). I have created a directory with 500,000 inodes (files) in it each of 18 characters long. The command line length is 9,500,000 characters. Created thus:
seq 1 500000 | while read digit; do
touch $(printf "abigfilename%06d\n" $digit);
done
And we note:
$ getconf ARG_MAX
2097152
Note however I can do this:
$ echo * > /dev/null
But this fails:
$ /bin/echo * > /dev/null
bash: /bin/echo: Argument list too long
I can run a for loop:
$ for f in *; do :; done
which is another shell builtin.
Careful reading of the documentation for ARG_MAX
states, Maximum length of argument to the exec functions. This means: Without calling exec
, there is no ARG_MAX
limitation. So it would explain why shell builtins are not restricted by ARG_MAX
.
And indeed, I can ls
my directory if my argument list is 109948 files long, or about 2,089,000 characters (give or take). Once I add one more 18-character filename file, though, then I get an Argument list too long error. So ARG_MAX
is working as advertised: the exec is failing with more than ARG_MAX
characters on the argument list- including, it should be noted, the environment data.
Yes, using DateFormat.getDateInstance(int style, Locale aLocale) This displays the current date in a locale-specific way.
So, for example:
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);
See the docs for the exact meaning of the style parameter (SHORT
, MEDIUM
, etc)
Using concept of unique hash keys :
my @array = ("a","b","c","b","a","d","c","a","d");
my %hash = map { $_ => 1 } @array;
my @unique = keys %hash;
print "@unique","\n";
Output: a c b d
I see there are already a ton of answers posted here, but I don’t think there’s any clear one yet that combines the already mentioned approaches into the one I’ve found to work. This is to make the link both appear disabled, and also not redirect the user to another page.
This answer assumes you’re using jquery and bootstrap, and uses another property to temporarily store the href
property while disabled.
//situation where link enable/disable should be toggled
function toggle_links(enable) {
if (enable) {
$('.toggle-link')
.removeClass('disabled')
.prop('href', $(this).attr('data-href'))
}
else {
$('.toggle-link')
.addClass('disabled')
.prop('data-href', $(this).prop('href'))
.prop('href','#')
}
a.disabled {
cursor: default;
}
I realize that an answer on a quite new solution is missing. If Numpy is used in the code, I would advice to try Pythran:
http://pythran.readthedocs.io/
For the functions I tried, Pythran gives extremely good results. The resulting functions are as fast as well written Fortran code (or only slightly slower) and a little bit faster than the (quite optimized) Cython solution.
The advantage compared to Cython is that you just have to use Pythran on the Python function optimized for Numpy, meaning that you do not have to expand the loops and add types for all variables in the loop. Pythran takes its time to analyse the code so it understands the operations on numpy.ndarray
.
It is also a huge advantage compared to Numba or other projects based on just-in-time compilation for which (to my knowledge), you have to expand the loops to be really efficient. And then the code with the loops becomes very very inefficient using only CPython and Numpy...
A drawback of Pythran: no classes! But since only the functions that really need to be optimized have to be compiled, it is not very annoying.
Another point: Pythran supports well (and very easily) OpenMP parallelism. But I don't think mpi4py is supported...
There's really no reason to remove ruby1-8, unless someone else knows better. Execute the commands below to install 1.9 and then link ruby to point to the new version.
sudo apt-get install ruby1-9 rubygems1-9
sudo ln -sf /usr/bin/ruby1-9 /usr/bin/ruby
From: jQuery text truncation (read more style)
Try this:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
And you can also use a plugin:
As a extension of String
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
Use as
"This is your title".trimToLength(10);
new
and delete
Note: This only deals with the syntax of overloading new
and delete
, not with the implementation of such overloaded operators. I think that the semantics of overloading new
and delete
deserve their own FAQ, within the topic of operator overloading I can never do it justice.
In C++, when you write a new expression like new T(arg)
two things happen when this expression is evaluated: First operator new
is invoked to obtain raw memory, and then the appropriate constructor of T
is invoked to turn this raw memory into a valid object. Likewise, when you delete an object, first its destructor is called, and then the memory is returned to operator delete
.
C++ allows you to tune both of these operations: memory management and the construction/destruction of the object at the allocated memory. The latter is done by writing constructors and destructors for a class. Fine-tuning memory management is done by writing your own operator new
and operator delete
.
The first of the basic rules of operator overloading – don’t do it – applies especially to overloading new
and delete
. Almost the only reasons to overload these operators are performance problems and memory constraints, and in many cases, other actions, like changes to the algorithms used, will provide a much higher cost/gain ratio than attempting to tweak memory management.
The C++ standard library comes with a set of predefined new
and delete
operators. The most important ones are these:
void* operator new(std::size_t) throw(std::bad_alloc);
void operator delete(void*) throw();
void* operator new[](std::size_t) throw(std::bad_alloc);
void operator delete[](void*) throw();
The first two allocate/deallocate memory for an object, the latter two for an array of objects. If you provide your own versions of these, they will not overload, but replace the ones from the standard library.
If you overload operator new
, you should always also overload the matching operator delete
, even if you never intend to call it. The reason is that, if a constructor throws during the evaluation of a new expression, the run-time system will return the memory to the operator delete
matching the operator new
that was called to allocate the memory to create the object in. If you do not provide a matching operator delete
, the default one is called, which is almost always wrong.
If you overload new
and delete
, you should consider overloading the array variants, too.
new
C++ allows new and delete operators to take additional arguments.
So-called placement new allows you to create an object at a certain address which is passed to:
class X { /* ... */ };
char buffer[ sizeof(X) ];
void f()
{
X* p = new(buffer) X(/*...*/);
// ...
p->~X(); // call destructor
}
The standard library comes with the appropriate overloads of the new and delete operators for this:
void* operator new(std::size_t,void* p) throw(std::bad_alloc);
void operator delete(void* p,void*) throw();
void* operator new[](std::size_t,void* p) throw(std::bad_alloc);
void operator delete[](void* p,void*) throw();
Note that, in the example code for placement new given above, operator delete
is never called, unless the constructor of X throws an exception.
You can also overload new
and delete
with other arguments. As with the additional argument for placement new, these arguments are also listed within parentheses after the keyword new
. Merely for historical reasons, such variants are often also called placement new, even if their arguments are not for placing an object at a specific address.
Most commonly you will want to fine-tune memory management because measurement has shown that instances of a specific class, or of a group of related classes, are created and destroyed often and that the default memory management of the run-time system, tuned for general performance, deals inefficiently in this specific case. To improve this, you can overload new and delete for a specific class:
class my_class {
public:
// ...
void* operator new();
void operator delete(void*,std::size_t);
void* operator new[](size_t);
void operator delete[](void*,std::size_t);
// ...
};
Overloaded thus, new and delete behave like static member functions. For objects of my_class
, the std::size_t
argument will always be sizeof(my_class)
. However, these operators are also called for dynamically allocated objects of derived classes, in which case it might be greater than that.
To overload the global new and delete, simply replace the pre-defined operators of the standard library with our own. However, this rarely ever needs to be done.
One simple method is to use place
to use an image as a background image. This is the type of thing that place
is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid
or pack
other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.
It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.
I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!
What you're looking for is scrollRectToVisible(_:animated:)
.
Example:
extension SignUpView: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
scrollView.scrollRectToVisible(textField.frame, animated: true)
}
}
What it does is exactly what you need, and it's far better than hacky contentOffset
This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.
From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible
Just edit the file "c:\wamp\alias\phpmyadmin.conf"
like this
<Directory "C:/wamp64/apps/phpmyadmin4.5.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
With the currently accepted solution you cannot print the page which contains the dialog itself anymore. Here's a much more dynamic solution:
JavaScript:
$().ready(function () {
$('.modal.printable').on('shown.bs.modal', function () {
$('.modal-dialog', this).addClass('focused');
$('body').addClass('modalprinter');
if ($(this).hasClass('autoprint')) {
window.print();
}
}).on('hidden.bs.modal', function () {
$('.modal-dialog', this).removeClass('focused');
$('body').removeClass('modalprinter');
});
});
CSS:
@media print {
body.modalprinter * {
visibility: hidden;
}
body.modalprinter .modal-dialog.focused {
position: absolute;
padding: 0;
margin: 0;
left: 0;
top: 0;
}
body.modalprinter .modal-dialog.focused .modal-content {
border-width: 0;
}
body.modalprinter .modal-dialog.focused .modal-content .modal-header .modal-title,
body.modalprinter .modal-dialog.focused .modal-content .modal-body,
body.modalprinter .modal-dialog.focused .modal-content .modal-body * {
visibility: visible;
}
body.modalprinter .modal-dialog.focused .modal-content .modal-header,
body.modalprinter .modal-dialog.focused .modal-content .modal-body {
padding: 0;
}
body.modalprinter .modal-dialog.focused .modal-content .modal-header .modal-title {
margin-bottom: 20px;
}
}
Example:
<div class="modal fade printable autoprint">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="window.print();">Print</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
Cross-platform support by using only pip
:
#!/usr/bin/env python
from sys import stderr
from pip.commands.uninstall import UninstallCommand
from pip import get_installed_distributions
pip_uninstall = UninstallCommand()
options, args = pip_uninstall.parse_args([
package.project_name
for package in
get_installed_distributions()
if not package.location.endswith('dist-packages')
])
options.yes = True # Don't confirm before uninstall
# set `options.require_venv` to True for virtualenv restriction
try:
print pip_uninstall.run(options, args)
except OSError as e:
if e.errno != 13:
raise e
print >> stderr, "You lack permissions to uninstall this package.
Perhaps run with sudo? Exiting."
exit(13)
# Plenty of other exceptions can be thrown, e.g.: `InstallationError`
# handle them if you want to.
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [@(result) stringValue];
Keep derived data but use the DSTROOT to specify the destination.
Use DEPLOYMENT_LOCATION to force deployment.
Use the undocumented DWARF_DSYM_FOLDER_PATH to copy the dSYM over too.
This allows you to use derived data location from xcodebuild and not have to do wacky stuff to find the app.
xcodebuild -sdk "iphoneos" -workspace Foo.xcworkspace -scheme Foo -configuration "Debug" DEPLOYMENT_LOCATION=YES DSTROOT=tmp DWARF_DSYM_FOLDER_PATH=tmp build
I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it
example:
Library ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error was resolved only after specifying the complete path, as it was not getting the callable function.
The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:
abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))
Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value
abs(qt(0.01/2, 40)) # 99% confidence, 2 sided
On Windows 10 you may use escape sequences this way:
#ifdef _WIN32
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
// print in red and restore colors default
std::cout << "\033[32m" << "Error!" << "\033[0m" << std::endl;
Use CryptoJS
Here's the code: https://github.com/odedhb/AES-encrypt
And here's an online working example: https://odedhb.github.io/AES-encrypt/
SQlite does not have a specific datetime type. You can use TEXT
, REAL
or INTEGER
types, whichever suits your needs.
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
- TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
- REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
- INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
SQLite built-in Date and Time functions can be found here.
Use command + m(cmd + M)
on MAC. Also make sure that you are accessing your application while you try to access the Debug Menu
i.e. your app must be running otherwise Cmd + M
will just return the usual ordinary phone menu.
I would choose the second as you don't have to do a copy of the memory and the Iterator works faster. So you save memory and time.
You don't need to --relocate
since the branch is within the same repository URL. Just do:
svn switch https://www.example.com/svn/branches/v1p2p3
Swift 4
var isModal: Bool {
return presentingViewController != nil ||
navigationController?.presentingViewController?.presentedViewController === navigationController ||
tabBarController?.presentingViewController is UITabBarController
}
Here is an updated macro based on the answer given above. This one should allow you to wrap your code even with a return statement.
#define SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(code) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
code; \
_Pragma("clang diagnostic pop") \
SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(
return [_target performSelector:_action withObject:self]
);
You can do git push --force
but be aware that you are rewriting history and anyone using the repo will have issue with this.
If you want to prevent this problem, don't use reset, but instead use git revert
int hour = your hour value;
int min = your minute value;
String ampm = your am/pm value;
hour = ampm == "AM" ? hour : (hour % 12) + 12; //convert 12-hour time to 24-hour
var dateTime = new DateTime(0,0,0, hour, min, 0);
var timeString = dateTime.ToString("HH:mm");
If you would like to work with a textbox, be aware that setting the TextMode property to "Date" will not work on Internet Explorer 11, because it does not currently support the "Date", "DateTime", nor "Time" values.
This example illustrates how to implement it using a textbox, including validation of the dates (since the user could enter just numbers). It will work on Internet Explorer 11 as well other web browsers.
<asp:Content ID="Content"
ContentPlaceHolderID="MainContent"
runat="server">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#
<%= txtBoxDate.ClientID %>").datepicker();
});
</script>
<asp:TextBox ID="txtBoxDate"
runat="server"
Width="135px"
AutoPostBack="False"
TabIndex="1"
placeholder="mm/dd/yyyy"
autocomplete="off"
MaxLength="10"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToValidate="txtBoxDate"
Operator="DataTypeCheck"
Type="Date">Date invalid, please check format.
</asp:CompareValidator>
</asp:Content>
My problem is that Flask-WTF is not resolved by PyCharm. I have tried to re-install and then install or Invalidate Cache and Restart PyCharm, but it's still not working.
Then I came up with this solution and it works perfectly for me.
Now, you'll see your library has been resolved.
-[NSString initWithData:encoding]
will return nil
if the specified encoding doesn't match the data's encoding.
Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).
Yes, you can use GROUP BY
:
SELECT time,
activities,
COUNT(*)
FROM table
GROUP BY time, activities;
You can recursively merge them into one as follows:
function mergeRecursive(obj1, obj2) {_x000D_
for (var p in obj2) {_x000D_
try {_x000D_
// Property in destination object set; update its value._x000D_
if (obj2[p].constructor == Object) {_x000D_
obj1[p] = this.mergeRecursive(obj1[p], obj2[p]);_x000D_
_x000D_
} else {_x000D_
obj1[p] = obj2[p];_x000D_
_x000D_
}_x000D_
_x000D_
} catch (e) {_x000D_
obj1[p] = obj2[p];_x000D_
_x000D_
}_x000D_
}_x000D_
return obj1;_x000D_
}_x000D_
_x000D_
arr1 = [_x000D_
{ id: "abdc4051", date: "2017-01-24" },_x000D_
{ id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
arr2 = [_x000D_
{ id: "abdc4051", name: "ab" },_x000D_
{ id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
mergeRecursive(arr1, arr2)_x000D_
console.log(JSON.stringify(arr1))
_x000D_
There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.
And See this question too : Generating SQL using XML and XSLT
Nathan Lee's answer is perfect. I just wanted to add something about position:absolute;
. If you wanted to use position:absolute;
like you had in your code, you have to think of it as pushing it away from one side of the page.
For example, if you wanted your div
to be somewhere in the bottom, you would have to use position:absolute; top:500px;
. That would push your div
500px from the top of the page. Same rule applies for all other directions.
For multiple select in Visual Studio Code, hold down the Alt key and starting clicking wherever you want to edit.
Visual Studio Code supports multiple line edit.
Maybe I am wrong, but as far as I can see Access-Control-Allow-Origin
has an "origin-list"
as parameter.
By definition an origin-list
is:
origin = "origin" ":" 1*WSP [ "null" / origin-list ]
origin-list = serialized-origin *( 1*WSP serialized-origin )
serialized-origin = scheme "://" host [ ":" port ]
; <scheme>, <host>, <port> productions from RFC3986
And from this, I argue different origins are admitted and should be space separated.
I suggest the following to make sure everything is uninstalled:
sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev
sudo apt-get purge mongodb-10gen
sudo apt-get autoremove
This should also remove your config from
/etc/mongodb.conf.
If you want to clean up completely and you might also want to remove the data directory
/var/lib/mongodb
You can achieve by this RunTime Attributes
we can make custom button.just see screenshot attached.
kindly pay attention :
in runtime attributes to change color of border follow this instruction
create category class of CALayer
in h file
@property(nonatomic, assign) UIColor* borderIBColor;
in m file:
-(void)setBorderIBColor:(UIColor*)color {
self.borderColor = color.CGColor;
}
-(UIColor*)borderIBColor {
return [UIColor colorWithCGColor:self.borderColor];
}
now onwards to set border color check screenshot
thanks
That's not how to add an item to a string. This:
newinv=inventory+str(add)
Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append()
method.
inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory
Hope this helps!
I think is this a very simple way with regards to all solutions above:
const elm = document.getElementById("myElement")
const allMyStyle = [
{ prop: "position", value: "fixed" },
{ prop: "boxSizing", value: "border-box" },
{ prop: "opacity", value: 0.9 },
{ prop: "zIndex", value: 1000 },
];
allMyStyle.forEach(({ prop, value }) => {
elm.style[prop] = value;
});
Will work for 100% sure. I had the same issue but its solved by below steps:
I hope this will work for all.
On NetBeans : open your project explorer->Dependencies->[file.jar] rightclick->Download Javadoc
As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema
namespace.
It takes a long time, and we did all the above solutions and they didn't work at all so our team decided to remove Pod
files and run pod install
again. finally, our OTA uploaded ipa installed on the user's device.
best Solution
clean project menu > Product > Clean Build Folder
and /Users/{you user name}/Library/Developer/Xcode/DerivedData
go to your project directory and remove Podfile.lock
,Pods
folder,pod_***.framework
run pod install
again
Done
Well you could attach a click or mousemove event to the document body that resets a timer. Have a function that you call at timed intervals that checks if the timer is over a specified time (like 1000 millis) and start your preloading.
document.getElementById('youridhere').click()
Getting HTML code from a website. You can use code like this.
string urlAddress = "http://google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (String.IsNullOrWhiteSpace(response.CharacterSet))
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code
This code will remove the indentation and list bullets.
ul {
padding: 0;
list-style-type: none;
}
By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean
, where you don't want to depend, but you need them to run before everything else.
I wrote the run-sequence
plugin specifically to fix this issue with gulp. After you install it, use it like this:
var runSequence = require('run-sequence');
gulp.task('develop', function(done) {
runSequence('clean', 'coffee', function() {
console.log('Run something else');
done();
});
});
You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously.
Please note, this will be (effectively) fixed in the next major release of gulp, as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence
to allow you to manually specify run order how you want.
However, that is a major breaking change, so there's no reason to wait when you can use run-sequence
today.
Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests
response header, indicating that the browser supports it (and in fact prefers it).
It took me 30mins of Googling, but I finally found it buried in the W3 spec.
The confusion comes because the header in the spec was HTTPS: 1
, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:
"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842
Their fix was to rename it to Upgrade-Insecure-Requests: 1
, and the spec has since been updated to match.
Anyway, here is the explanation from the W3 spec (as it appeared at the time)...
The
HTTPS
HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide....
When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.
When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a
Strict-Transport-Security
header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].
Julien Danjou wrote a good article explaining why you should never deal with timezones. An excerpt:
Indeed, Python datetime API always returns unaware datetime objects, which is very unfortunate. Indeed, as soon as you get one of this object, there is no way to know what the timezone is, therefore these objects are pretty "useless" on their own.
Alas, even though you may use utcnow()
, you still won't see the timezone info, as you discovered.
Recommendations:
Always use aware
datetime
objects, i.e. with timezone information. That makes sure you can compare them directly (aware and unawaredatetime
objects are not comparable) and will return them correctly to users. Leverage pytz to have timezone objects.Use ISO 8601 as the input and output string format. Use
datetime.datetime.isoformat()
to return timestamps as string formatted using that format, which includes the timezone information.If you need to parse strings containing ISO 8601 formatted timestamps, you can rely on
iso8601
, which returns timestamps with correct timezone information. This makes timestamps directly comparable.
I find lots of answer for this kind of question misleading
Modified from this post: https://www.webmasterworld.com/linux/3613813.htm
The following code will create bash window and works exactly as a bash window. Hope this helps. Too many wrong/not-working answers out there...
Process proc;
try {
//create a bash window
proc = Runtime.getRuntime().exec("/bin/bash");
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
BufferedReader err = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));
//input into the bash window
out.println("cd /my_folder");
out.println("rm *.jar");
out.println("svn co path to repo");
out.println("mvn compile package install");
out.println("exit");
String line;
System.out.println("----printing output-----");
while ((line = in.readLine()) != null) {
System.out.println(line);
}
while((line = err.readLine()) != null) {
//read errors
}
proc.waitFor();
in.close();
out.close();
err.close();
proc.destroy();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Based in marksyzm answer, this worked for me:
$('input').datepicker({
beforeShow:function(input) {
$(input).css({
"position": "relative",
"z-index": 999999
});
}
});
If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.
The simplest answer to the meaning of deprecated
when used to describe software APIs is:
- Stop using APIs marked as deprecated!
- They will go away in a future release!!
- Start using the new versions ASAP!!!
Something I've noticed - in the INFORMATION_SCHEMA.COLUMNS view, CHARACTER_MAXIMUM_LENGTH gives a size of 2147483647 (2^31-1) for field types such as image and text. ntext is 2^30-1 (being double-byte unicode and all).
This size is included in the output from this query, but it is invalid for these data types in a CREATE statement (they should not have a maximum size value at all). So unless the results from this are manually corrected, the CREATE script won't work given these data types.
I imagine it's possible to fix the script to account for this, but that's beyond my SQL capabilities.
Finding of week number for each date of a month (considering Monday as beginning of the week)
Keep the first date of month contant $B$13
=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1
WEEKNUM(B18,2)
- returns the week number of the date mentioned in cell B18
WEEKNUM($B$13,2)
- returns the week number of the 1st date of month in cell B13
Many of the answers here are wrong. It seems people figure out what was causing status==0 in their particular case and then generalize that as the answer.
Practically speaking, status==0 for a failed XmlHttpRequest should be considered an undefined error.
The actual W3C spec defines the conditions for which zero is returned here: https://fetch.spec.whatwg.org/#concept-network-error
As you can see from the spec (fetch or XmlHttpRequest) this code could be the result of an error that happened even before the server is contacted.
Some of the common situations that produce this status code are reflected in the other answers but it could be any or none of these problems:
What would be helpful would be for browsers to provide detailed error reporting for more of these status==0 scenarios. Indeed, sometimes status==0 will accompany a helpful console message, but in others there is no other information.
Simple:
st = "abcdefghij"
st = st[:-1]
There is also another way that shows how it is done with steps:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
This is also a way with user input:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
To make it take away the last word in a list:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
Check with your bean class. Column data type and bean datatype must be same.
Can you not use like this?
@Query("SELECT DISTINCT name FROM people p (nolock) WHERE p.name NOT IN (:myparam)")
List<String> findNonReferencedNames(@Param("myparam")List<String> names);
P.S. I write queries in SQL Server 2012 a lot and using nolock
in server is a good practice, you can ignore nolock
if a local db is used.
Seems like your db name is not being mapped correctly (after you've updated your question)
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
Use df.to_dict('records')
-- gives the output without having to transpose externally.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
As the commenters for the previous answer mentioned, you cannot simply add the line...
<location path="." inheritInChildApplications="false">
...just below <configuration>
. Instead, you need to wrap the individual web.config sections for which you want to disable inheritance. For example:
<!-- disable inheritance for the connectionStrings section -->
<location path="." inheritInChildApplications="false">
<connectionStrings>
</connectionStrings>
</location>
<!-- leave inheritance enabled for appSettings -->
<appSettings>
</appSettings>
<!-- disable inheritance for the system.web section -->
<location path="." inheritInChildApplications="false">
<system.web>
<webParts>
</webParts>
<membership>
</membership>
<compilation>
</compilation>
</system.web>
</location>
While <clear />
may work for some configuration sections, there are some that instead require a <remove name="...">
directive, and still others don't seem to support either. In these situations, it's probably appropriate to set inheritInChildApplications="false"
.
It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.
df <- data.frame(
X1=seq(0, 5, by=0.001),
X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)
# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf),
labels = c("low", "medium", "high"),
right = FALSE)
### Base Graphics
plot(df$X1, df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 21)
plot(df$X1,df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)
# Using `with()`
with(df,
plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
)
# Using ggplot2
library(ggplot2)
# qplot()
qplot(df$X1, df$X2, colour = df$Colour)
# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour))
p <- p + geom_point() + xlab("POS") + ylab("CS")
p
p + facet_grid(Colour~., scales = "free")
I've compared the suggested alternative for speed and found that, surprisingly, the void view unique
solution is even a bit faster than numpy's native unique
with the axis
argument. If you're looking for speed, you'll want
numpy.unique(
a.view(numpy.dtype((numpy.void, a.dtype.itemsize*a.shape[1])))
).view(a.dtype).reshape(-1, a.shape[1])
There is a bug report on GitHub for this, too.
Code to reproduce the plot:
import numpy
import perfplot
def unique_void_view(a):
return (
numpy.unique(a.view(numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1]))))
.view(a.dtype)
.reshape(-1, a.shape[1])
)
def lexsort(a):
ind = numpy.lexsort(a.T)
return a[
ind[numpy.concatenate(([True], numpy.any(a[ind[1:]] != a[ind[:-1]], axis=1)))]
]
def vstack(a):
return numpy.vstack([tuple(row) for row in a])
def unique_axis(a):
return numpy.unique(a, axis=0)
perfplot.show(
setup=lambda n: numpy.random.randint(2, size=(n, 20)),
kernels=[unique_void_view, lexsort, vstack, unique_axis],
n_range=[2 ** k for k in range(15)],
xlabel="len(a)",
equality_check=None,
)
public static bool CheckFiles(string pathA, string pathB)
{
string[] extantionFormat = new string[] { ".war", ".pkg" };
return CheckFiles(pathA, pathB, extantionFormat);
}
public static bool CheckFiles(string pathA, string pathB, string[] extantionFormat)
{
System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(pathA);
System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(pathB);
// Take a snapshot of the file system. list1/2 will contain only WAR or PKG
// files
// fileInfosA will contain all of files under path directories
FileInfo[] fileInfosA = dir1.GetFiles("*.*",
System.IO.SearchOption.AllDirectories);
// list will contain all of files that have ..extantion[]
// Run on all extantion in extantion array and compare them by lower case to
// the file item extantion ...
List<System.IO.FileInfo> list1 = (from extItem in extantionFormat
from fileItem in fileInfosA
where extItem.ToLower().Equals
(fileItem.Extension.ToLower())
select fileItem).ToList();
// Take a snapshot of the file system. list1/2 will contain only WAR or
// PKG files
// fileInfosA will contain all of files under path directories
FileInfo[] fileInfosB = dir2.GetFiles("*.*",
System.IO.SearchOption.AllDirectories);
// list will contain all of files that have ..extantion[]
// Run on all extantion in extantion array and compare them by lower case to
// the file item extantion ...
List<System.IO.FileInfo> list2 = (from extItem in extantionFormat
from fileItem in fileInfosB
where extItem.ToLower().Equals
(fileItem.Extension.ToLower())
select fileItem).ToList();
FileCompare myFileCompare = new FileCompare();
// This query determines whether the two folders contain
// identical file lists, based on the custom file comparer
// that is defined in the FileCompare class.
return list1.SequenceEqual(list2, myFileCompare);
}
I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.
Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.
In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.
Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.
For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :
20/2 = 10
10/2 = 5
Hence our answer is 5 + 1 + 1 = 7
. (The 1 + 1 because we divided the number 20 twice).
Package Explorer / View Menu / Package Presentation... / Hierarchical
The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.