Or you could just use justify-content: flex-end
.main { display: flex; }
.c { justify-content: flex-end; }
The Node.js Documentation offers a very elegant example using the Readline module.
Example: Read File Stream Line-by-Line
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
console.log(`Line from file: ${line}`);
});
Note: we use the crlfDelay option to recognize all instances of CR LF ('\r\n') as a single line break.
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
Also:
You can verify the number of visible cells using this function:
- (NSArray *)visibleCells
This method will return an array with the cells that are visible, so you can count the number of objects in this array and compare with the number of objects in your table.. if it's equal.. you can disable the scrolling using:
tableView.scrollEnabled = NO;
As @Ginny mentioned.. we would can have problems with partially visible cells, so this solution works better in this case:
tableView.scrollEnabled = (tableView.contentSize.height <= CGRectGetHeight(tableView.frame));
In case you are using autoLayout this solution do the job:
tableView.alwaysBounceVertical = NO.
Once you are able to parse those strings into a Date object comparing them is easy (Using the <
operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.
Just saw it on a website and seems to work on latest Android with latest chrome and whatsapp now too! Give the link a new shot!
<a href="whatsapp://send?text=The text to share!" data-action="share/whatsapp/share">Share via Whatsapp</a>
Rechecked it today (17th April 2015):
Works for me on iOS 8 (iPhone 6, latest versions) Android 5 (Nexus 5, latest versions).
It also works on Windows Phone.
Set it in the body selector of your css. E.g.
body {
font: 16px Arial, sans-serif;
}
Here is an example of using flex that also works in Internet Explorer 11 and Chrome.
HTML
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
<style>_x000D_
html, body {_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
height: 100vh;_x000D_
}_x000D_
.main {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-ms-flex-direction: row;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
min-height: 100vh;_x000D_
}_x000D_
_x000D_
.main::after {_x000D_
content: '';_x000D_
height: 100vh;_x000D_
width: 0;_x000D_
overflow: hidden;_x000D_
visibility: hidden;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.left {_x000D_
width: 200px;_x000D_
background: #F0F0F0;_x000D_
flex-shrink: 0;_x000D_
}_x000D_
_x000D_
.right {_x000D_
flex-grow: 1;_x000D_
background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="main">_x000D_
<div class="left">_x000D_
<div style="height: 300px;">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="right">_x000D_
<div style="height: 1000px;">_x000D_
test test test_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is
client.onreadystatechange = function() {
and in danb's case, it is
function(data) {
This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.
This worked for me:
#!/bin/bash
git add `git status | grep modified | sed 's/\(.*modified:\s*\)//'`
Or even better:
$ git ls-files --modified | xargs git add
BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.
Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.
When writing datetime value to sql db
//Convert the time into UTC and build Timestamp object.
Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
//use setTimestamp on preparedstatement
preparedStatement.setTimestamp(1, ts);
When reading the value back from DB into java,
Then, change it to your desired timezone. Here I am changing it to Toronto timezone.
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
Timestamp timestamp = resultSet.getTimestamp(1);
ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
I've used the following JavaScript library with great success:
https://github.com/balupton/jquery-history
It supports the HTML5 history API as well as a fallback method (using #) for older browsers.
This library is essentially a polyfill around `history.pushState'.
From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.
To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.
In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
For those looking concise answer.
Both
ref
andout
keywords are used to pass-by-reference
.
A variable of
ref
keyword must have a value or must refer to an object ornull
before its passing.
Unlike
ref
, a variable ofout
keyword must have a value or must refer to an object ornull
after its passing as well as no need to have a value or refer to an object before passing.
To get first object from array of objects by a specific property value:
function getObjectFromObjectsArrayByPropertyValue(objectsArray, propertyName, propertyValue) {_x000D_
return objectsArray.find(function (objectsArrayElement) {_x000D_
return objectsArrayElement[propertyName] == propertyValue;_x000D_
});_x000D_
}_x000D_
_x000D_
function findObject () {_x000D_
var arrayOfObjectsString = document.getElementById("arrayOfObjects").value,_x000D_
arrayOfObjects,_x000D_
propertyName = document.getElementById("propertyName").value,_x000D_
propertyValue = document.getElementById("propertyValue").value,_x000D_
preview = document.getElementById("preview"),_x000D_
searchingObject;_x000D_
_x000D_
arrayOfObjects = JSON.parse(arrayOfObjectsString);_x000D_
_x000D_
console.debug(arrayOfObjects);_x000D_
_x000D_
if(arrayOfObjects && propertyName && propertyValue) {_x000D_
searchingObject = getObjectFromObjectsArrayByPropertyValue(arrayOfObjects, propertyName, propertyValue);_x000D_
if(searchingObject) {_x000D_
preview.innerHTML = JSON.stringify(searchingObject, false, 2);_x000D_
} else {_x000D_
preview.innerHTML = "there is no object with property " + propertyName + " = " + propertyValue + " in your array of objects";_x000D_
}_x000D_
}_x000D_
}
_x000D_
pre {_x000D_
padding: 5px;_x000D_
border-radius: 4px;_x000D_
background: #f3f2f2;_x000D_
}_x000D_
_x000D_
textarea, button {_x000D_
width: 100%_x000D_
}
_x000D_
<fieldset>_x000D_
<legend>Input Data:</legend>_x000D_
<label>Put here your array of objects</label>_x000D_
<textarea rows="7" id="arrayOfObjects">_x000D_
[_x000D_
{"a": 1, "b": 2},_x000D_
{"a": 3, "b": 4},_x000D_
{"a": 5, "b": 6},_x000D_
{"a": 7, "b": 8, "c": 157}_x000D_
]_x000D_
</textarea>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<label>property name: </label> <input type="text" id="propertyName" value="b"/>_x000D_
<label>property value: </label> <input type="text" id="propertyValue" value=6 />_x000D_
_x000D_
</fieldset>_x000D_
<hr>_x000D_
<button onclick="findObject()">find object in array!</button>_x000D_
<hr>_x000D_
<fieldset>_x000D_
<legend>Searching Result:</legend>_x000D_
<pre id="preview">click find</pre>_x000D_
</fieldset>
_x000D_
Or you could just do it that way:
public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
....
}
That works for example for forms like this:
<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />
This is the simplest solution :)
function createOfferUrlArray($Offer) {
$offerArray = array();
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
return $offerArray;
}
or
function createOfferUrlArray($offer) {
foreach ( $offer as &$value ) {
$value = $value[4];
}
unset($value);
return $offer;
}
Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if
statement allows you to create a main
function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.
To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar:
and def foobar()
creates either a class or a function and stores them in memory for later use.
JavaScript way - this worked for me.
<script>
$(document).ready(function() {
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>
Reason:
$('#YourTableId').find('*')
-> this returns all the tags.
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
iterates over all objects captured in this and disable input tags.
Analysis (Debugging):
form:radiobutton
is internally considered as an "input" tag.
Like in the above function(), if you try printing document.write(this.tagName);
Wherever, in tags it finds radio buttons, it returns an input tag.
So, above code line can be more optimized for radio button tags, by replacing * with input:
$('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });
or you can also do ( for pem file )
scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/
Found a fix. (If you are using proxy on your network) //Windows 1. Open control panel 2. Network and internet 3. Network and sharing center 4. On the bottom left side of the window, you will see Internet Options, under connections tab, click LAN settings check the bypass
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.
As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.
Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...
# fooz.yml
foo:
bar: <%= $ENV[:some_var] %>
No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.
If you can use the template like that or the << >>
or the {{ }}
styles depending on your reader, after that you just ...
In another yml file ...
# boo.yml
development:
fooz: foo
Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.
Here's a little method I wrote for exactly this purpose. It uses Validate from Apache Commons.
Feel free to use it.
/**
* Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
* the value of the key to be used and the object itself from the list entry is used as the
* objct. An empty <code>Map</code> is returned upon null input.
* Reflection is used to retrieve the key from the object instance and method name passed in.
*
* @param <K> The type of the key to be used in the map
* @param <V> The type of value to be used in the map and the type of the elements in the
* collection
* @param coll The collection to be converted.
* @param keyType The class of key
* @param valueType The class of the value
* @param keyMethodName The method name to call on each instance in the collection to retrieve
* the key
* @return A map of key to value instances
* @throws IllegalArgumentException if any of the other paremeters are invalid.
*/
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
final Class<K> keyType,
final Class<V> valueType,
final String keyMethodName) {
final HashMap<K, V> map = new HashMap<K, V>();
Method method = null;
if (isEmpty(coll)) return map;
notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));
try {
// return the Method to invoke to get the key for the map
method = valueType.getMethod(keyMethodName);
}
catch (final NoSuchMethodException e) {
final String message =
String.format(
Messages.getString(METHOD_NOT_FOUND),
keyMethodName,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
try {
for (final V value : coll) {
Object object;
object = method.invoke(value);
@SuppressWarnings("unchecked")
final K key = (K) object;
map.put(key, value);
}
}
catch (final Exception e) {
final String message =
String.format(
Messages.getString(METHOD_CALL_FAILED),
method,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
return map;
}
Background image fix to screens with browser compatibility css
.full-screen {
height: 100%;
width: 100%;
background-image: url(../images/banner.jpg);
background-size: cover;
background-position: center;
//for browser compatibility
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
}
Javascripts .call()
and .apply()
methods allow you to set the context for a function.
var myfunc = function(){
alert(this.name);
};
var obj_a = {
name: "FOO"
};
var obj_b = {
name: "BAR!!"
};
Now you can call:
myfunc.call(obj_a);
Which would alert FOO
. The other way around, passing obj_b
would alert BAR!!
. The difference between .call()
and .apply()
is that .call()
takes a comma separated list if you're passing arguments to your function and .apply()
needs an array.
myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);
Therefore, you can easily write a function hook
by using the apply()
method. For instance, we want to add a feature to jQuerys .css()
method. We can store the original function reference, overwrite the function with custom code and call the stored function.
var _css = $.fn.css;
$.fn.css = function(){
alert('hooked!');
_css.apply(this, arguments);
};
Since the magic arguments
object is an array like object, we can just pass it to apply()
. That way we guarantee, that all parameters are passed through to the original function.
generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn" with theses parameters, you can do it a simple request. in the service, eg. .net
jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
from tbANyThing tt
where id > lastIdObtained
order by id
}
In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got
I was struggling since a couple of hours for this issue because i was putting that file under resources folder but it didn't help me, finally i realized my mistake. Put it directly under src/main/java.
This is rather long post and it gives a more detailed explanation of the issue.
The problem (in my case) comes when you have Multi Slot Content Projection
See also content projection for more info.
For example If you have a component which looks like this:
html file:
<div>
<span>
<ng-content select="my-component-header">
<!-- optional header slot here -->
</ng-content>
</span>
<div class="my-component-content">
<ng-content>
<!-- content slot here -->
</ng-content>
</div>
</div>
ts file:
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
})
export class MyComponent {
}
And you want to use it like:
<my-component>
<my-component-header>
<!-- this is optional -->
<p>html content here</p>
</my-component-header>
<p>blabla content</p>
<!-- other html -->
</my-component>
And then you get template parse errors that is not a known Angular component and the matter of fact it isn't - it is just a reference to an ng-content in your component:
And then the simplest fix is adding
schemas: [
CUSTOM_ELEMENTS_SCHEMA
],
... to your app.module.ts
But there is an easy and clean approach to this problem - instead of using <my-component-header>
to insert html in the slot there - you can use a class name for this task like this:
html file:
<div>
<span>
<ng-content select=".my-component-header"> // <--- Look Here :)
<!-- optional header slot here -->
</ng-content>
</span>
<div class="my-component-content">
<ng-content>
<!-- content slot here -->
</ng-content>
</div>
</div>
And you want to use it like:
<my-component>
<span class="my-component-header"> // <--- Look Here :)
<!-- this is optional -->
<p>html content here</p>
</span>
<p>blabla content</p>
<!-- other html -->
</my-component>
So ... no more components that do not exist so there are no problems in that, no errors, no need for CUSTOM_ELEMENTS_SCHEMA in app.module.ts
For more info about this issue - https://github.com/angular/angular/issues/11251
For more info about Angular content projection - https://blog.angular-university.io/angular-ng-content/
You can see also https://scotch.io/tutorials/angular-2-transclusion-using-ng-content
Simple in two line
Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class
TweenAnimationBuilder<Duration>(
duration: Duration(minutes: 3),
tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
onEnd: () {
print('Timer ended');
},
builder: (BuildContext context, Duration value, Widget child) {
final minutes = value.inMinutes;
final seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$minutes:$seconds',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)));
}),
and You also get onEnd call back which notifies you when the animation completes;
here's the output
What blowdart said, but with a little less code. Use Linq or CopyTo
to concatenate arrays.
public static byte[] Hash(string value, byte[] salt)
{
return Hash(Encoding.UTF8.GetBytes(value), salt);
}
public static byte[] Hash(byte[] value, byte[] salt)
{
byte[] saltedValue = value.Concat(salt).ToArray();
// Alternatively use CopyTo.
//var saltedValue = new byte[value.Length + salt.Length];
//value.CopyTo(saltedValue, 0);
//salt.CopyTo(saltedValue, value.Length);
return new SHA256Managed().ComputeHash(saltedValue);
}
Linq has an easy way to compare your byte arrays too.
public bool ConfirmPassword(string password)
{
byte[] passwordHash = Hash(password, _passwordSalt);
return _passwordHash.SequenceEqual(passwordHash);
}
Before implementing any of this however, check out this post. For password hashing you may want a slow hash algorithm, not a fast one.
To that end there is the Rfc2898DeriveBytes
class which is slow (and can be made slower), and may answer the second part of the original question in that it can take a password and salt and return a hash. See this question for more information. Note, Stack Exchange is using Rfc2898DeriveBytes
for password hashing (source code here).
This can be addressed simple by CSS attribute:
XML:
<label name="pageTac"> Hello how are you doing?
Thank you I'm Good</label>
CSS
.pageText{
white-space:pre !important; // this wraps the xml text.}
HTML / XSL
<tr>
<td class="pageText"><xsl:value-of select="$Dictionary/infolabels/label[@name='pageTac']" />
</td></tr>
Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first)
is slowed down by that evaluation.
An equally fast and easy to read solution is using the function version .not(":first")
:
e.g.
$("li").not(":first").hide();
JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
This is only few percentage points slower than slice(1)
, but is very readable as "I want all except the first one".
Update: text-overflow: ellipsis
is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.
Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.
Note this technique also prevents updating the content of the node in JavaScript using the innerHTML
property in Firefox. See the end of this post for a workaround.
CSS
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}
ellipsis.xml
file contents
<?xml version="1.0"?>
<bindings
xmlns="http://www.mozilla.org/xbl"
xmlns:xbl="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
<binding id="ellipsis">
<content>
<xul:window>
<xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
</xul:window>
</content>
</binding>
</bindings>
Updating node content
To update the content of a node in a way that works in Firefox use the following:
var replaceEllipsis(node, content) {
node.innerHTML = content;
// use your favorite framework to detect the gecko browser
if (YAHOO.env.ua.gecko) {
var pnode = node.parentNode,
newNode = node.cloneNode(true);
pnode.replaceChild(newNode, node);
}
};
See Matt Snider's post for an explanation of how this works.
The sequence is CR (Carriage Return) - LF (Line Feed). Remember dot matrix printers? Exactly. So - the correct order is \r \n
In my code I use DATETIME DEFAULT CURRENT_TIMESTAMP
as the type and constraint of the column.
In your case your table definition would be
create table notes (
_id integer primary key autoincrement,
created_date date default CURRENT_DATE
)
It doesn't matter what you use as a primary key so long as it is UNIQUE. If you care about speed or good database design use the int unless you plan on replicating data, then use a GUID.
If this is an access database or some tiny app then who really cares. I think the reason why most of us developers slap the old int or guid at the front is because projects have a way of growing on us, and you want to leave yourself the option to grow.
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.
public static bool IsConnected(this Socket client)
{
bool blockingState = client.Blocking;
try
{
byte[] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
return true;
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
return true;
}
else
{
return false;
}
}
finally
{
client.Blocking = blockingState;
}
}
Above methods didn´t work for me. This did:
Dim arrayIsNothing As Boolean
On Error Resume Next
arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
If Err.Number <> 0 Then arrayIsNothing = True
Err.Clear
On Error GoTo 0
'Now you can test:
if arrayIsNothing then ...
You would need to know how to identify an error in your results. If you do not have a standard expected error, I suggest that you run a transformation on each error in the catch block that makes it identifiable in your results.
try {
let resArray = await Promise.all(
state.routes.map(route => route.handler.promiseHandler().catch(e => e))
);
// in catch(e => e) you can transform your error to a type or object
// that makes it easier for you to identify whats an error in resArray
// e.g. if you expect your err objects to have e.type, you can filter
// all errors in the array eg
// let errResponse = resArray.filter(d => d && d.type === '<expected type>')
// let notNullResponse = resArray.filter(d => d)
} catch (err) {
// code related errors
}
Try this.
SELECT * FROM la_schedule WHERE `start_date` > '2012-11-18';
Sometimes it can be dangerous to convert charsets, specially on databases with huge amounts of data. I think the best option is to use the "binary" operator:
e.g : WHERE binary table1.column1 = binary table2.column1
The STAThreadAttribute
is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.
MSDN explains the reason in slightly more detail:
STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.
This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).
Here's an example of posting form data to add a user to a database. Check request.method == "POST"
to check if the form was submitted. Use keys from request.form
to get the form data. Render an HTML template with a <form>
otherwise. The fields in the form should have name
attributes that match the keys in request.form
.
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/user/add", methods=["GET", "POST"])
def add_user():
if request.method == "POST":
user = User(
username=request.form["username"],
email=request.form["email"],
)
db.session.add(user)
db.session.commit()
return redirect(url_for("index"))
return render_template("add_user.html")
<form method="post">
<label for="username">Username</label>
<input type="text" name="username" id="username">
<label for="email">Email</label>
<input type="email" name="email" id="email">
<input type="submit">
</form>
An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options
(A) Write a custom 'delete' function for your array like (untested)
Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
Dim i As Integer
' Move all element back one position
For i = index + 1 To UBound(prLst)
prLst(i - 1) = prLst(i)
Next
' Shrink the array by one, removing the last one
ReDim Preserve prLst(Len(prLst) - 1)
End Sub
(B) Simply set a 'dummy' value as the value instead of actually deleting the element
If prLst(eachHdr) = "0" Then
prLst(eachHdr) = "n/a"
End If
(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from
Dim prLst As New Collection
Via css. Put this inside the <head>
tag.
<style type="text/css" media="screen">
table{
border-collapse:collapse;
border:1px solid #FF0000;
}
table td{
border:1px solid #FF0000;
}
</style>
Apparently, you can now use NLog with Growl for Windows.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="NLog.Targets.GrowlNotify" />
</extensions>
<targets>
<target name="growl" type="GrowlNotify" password="" host="" port="" />
</targets>
<rules>
<logger name="*" minLevel="Trace" appendTo="growl"/>
</rules>
</nlog>
The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:
$scope.radioMod = 1;
$scope.radioMod2 = 2;
Here is a representation of the new html:
<label data-ng-repeat="choice2 in question2.choices">
<input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
{{choice2.text}}
</label>
As someone whose career focused on Windows enterprise development from 1997 - 2010, the obvious answer would be PowerShell for all the good reasons given previously (e.g., it is part of Microsoft's enterprise strategy; it integrates well with Windows/COM/.NET; and using objects instead of files provides for a "richer" coding model). For that reason I'd been using and promoting PowerShell for the last two years or so, with the express belief I was following the "Word of Bill."
However, as a pragmatist I'm no longer sure PowerShell is such a great answer. While it's an excellent Windows tool and provides a much needed step towards filling the historic hole that is the Window command line, as we all watch Microsoft's grip on consumer computing slip it seems increasingly likely that Microsoft has a massive battle ahead to keep its OS as important to the enterprise of the future.
Indeed, given I find my work is increasingly in heterogeneous environments, I'm finding it much more useful to use Bash scripts at the moment, as they not only work on Linux, Solaris and Mac OS X, but they also work—with the help of Cygwin—on Windows.
So if you buy into the belief that the future of the OS is commoditized rather than a monopolized, then it seems to make sense to opt for an agile development tool strategy that keeps away from proprietary tools where feasible. If however you see your future being dominated by all-that-is-Redmond then go for PowerShell.
I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.
Here's my code behind a command button
Private Sub cmdSave()
Dim sFileName As String
Dim WB As Workbook
Application.DisplayAlerts = False
sFileName = "MyFileName.csv"
'Copy the contents of required sheet ready to paste into the new CSV
Sheets(1).Range("A1:T85").Copy 'Define your own range
'Open a new XLS workbook, save it as the file name
Set WB = Workbooks.Add
With WB
.Title = "MyTitle"
.Subject = "MySubject"
.Sheets(1).Select
ActiveSheet.Paste
.SaveAs "MyDirectory\" & sFileName, xlCSV
.Close
End With
Application.DisplayAlerts = True
End Sub
This works for me :-)
For people who have come here to look for a general answer for duplicate row removal, use !duplicated()
:
a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)
duplicated(df)
[1] FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE
> df[duplicated(df), ]
a b
2 A 1
6 B 1
8 C 2
> df[!duplicated(df), ]
a b
1 A 1
3 A 2
4 B 4
5 B 1
7 C 2
Answer from: Removing duplicated rows from R data frame
That's not true Jeff.
You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.
Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.
You can, of course, achieve the same by providing web.config entries (or files) as needed.
Edit: removed a confusing sentence :)
I want to add that when using Windows you can use require './1.rb'
if the script is run local or from a mapped network drive but when run from an UNC \\servername\sharename\folder
path you need to use require_relative './1.rb'
.
I don't mingle in the discussion which to use for other reasons.
I collected some ideas from other SO question (largely from here and this css page)
The idea is to use relative and absolute positioning to move your line to the bottom:
@media (min-width: 768px ) {
.row {
position: relative;
}
#bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}}
The display:flex
option is at the moment a solution to make the div get the same size as its parent. This breaks on the other hand the bootstrap possibilities to auto-linebreak on small devices by adding col-sx-12
class. (This is why the media query is needed)
To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):
var minutes = Math.floor(time / 60);
And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:
var seconds = time - minutes * 60;
Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:
var hours = Math.floor(time / 3600);
time = time - hours * 3600;
Then you calculate the full minutes and remaining seconds.
Bonus:
Use the following code to pretty-print the time (suggested by Dru)
function str_pad_left(string,pad,length) {
return (new Array(length+1).join(pad)+string).slice(-length);
}
var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
When facing errors with input files of any type, encoding issues are common.
A simple solution might be to open a new file, copy pasting your CSV text in it, then saving it as a new file.
Perhaps this is what you are looking for:
import os
os.chdir(default_path)
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
Placing @EdChum's very nice answer into a function count_unique_index
.
The unique method only works on pandas series, not on data frames.
The function below reproduces the behavior of the unique function in R:
unique returns a vector, data frame or array like x but with duplicate elements/rows removed.
And adds a count of the occurrences as requested by the OP.
df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],
'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})
def count_unique_index(df, by):
return df.groupby(by).size().reset_index().rename(columns={0:'count'})
count_unique_index(df1, ['A','B'])
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
To send mail through SQL Server we need to set up DB mail profile we can either use T-SQl or SQL Database mail option in sql server to create profile. After below code is used to send mail through query or stored procedure.
Use below link to create DB mail profile
http://www.freshcodehub.com/Article/42/configure-database-mail-in-sql-server-database
http://www.freshcodehub.com/Article/43/create-a-database-mail-configuration-using-t-sql-script
--Sending Test Mail_x000D_
EXEC msdb.dbo.sp_send_dbmail_x000D_
@profile_name = 'TestProfile', _x000D_
@recipients = 'To Email Here', _x000D_
@copy_recipients ='CC Email Here', --For CC Email if exists_x000D_
@blind_copy_recipients= 'BCC Email Here', --For BCC Email if exists_x000D_
@subject = 'Mail Subject Here', _x000D_
@body = 'Mail Body Here',_x000D_
@body_format='HTML',_x000D_
@importance ='HIGH',_x000D_
@file_attachments='C:\Test.pdf'; --For Attachments if exists
_x000D_
If you want to change your number into a list of those numbers, I would first cast it to a string
, then casting it to a list will naturally break on each character:
[int(x) for x in str(n)]
The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.
If you want to avoid this problem then use a more appropriate data type. decimal
will do what you want:
Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)
Result: 0.58
The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).
Edit to add:
Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875
You can see from this why rounding give 0.57.
Shows all the stored procedures:
SHOW PROCEDURE STATUS;
Shows all the functions:
SHOW FUNCTION STATUS;
Shows the definition of the specified procedure:
SHOW CREATE PROCEDURE [PROC_NAME];
Shows you all the procedures of the given database:
SHOW PROCEDURE STATUS WHERE Db = '[db_name]';
The best way to check for named elements is to use exist()
, however the above answers are not using the function properly. You need to use the where
argument to check for the variable within the list.
foo <- list(a=42, b=NULL)
exists('a', where=foo) #TRUE
exists('b', where=foo) #TRUE
exists('c', where=foo) #FALSE
To work with NpgsqlCommand or the standard sqlCommand use:
int result = int.Parse(cmd.ExecuteScalar().ToString());
Recently I was learning about chrono library and thought of implementing a sleep function on my own. Here is the code,
#include <cmath>
#include <chrono>
template <typename rep = std::chrono::seconds::rep,
typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
using sleep_duration = std::chrono::duration<long double, std::nano>;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
long double elapsed_time =
std::chrono::duration_cast<sleep_duration>(end - start).count();
long double sleep_time =
std::chrono::duration_cast<sleep_duration>(sec).count();
while (std::isgreater(sleep_time, elapsed_time)) {
end = std::chrono::steady_clock::now();
elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count();
}
}
We can use it with any std::chrono::duration
type (By default it takes std::chrono::seconds
as argument). For example,
#include <cmath>
#include <chrono>
template <typename rep = std::chrono::seconds::rep,
typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
using sleep_duration = std::chrono::duration<long double, std::nano>;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
long double elapsed_time =
std::chrono::duration_cast<sleep_duration>(end - start).count();
long double sleep_time =
std::chrono::duration_cast<sleep_duration>(sec).count();
while (std::isgreater(sleep_time, elapsed_time)) {
end = std::chrono::steady_clock::now();
elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count();
}
}
using namespace std::chrono_literals;
int main (void) {
std::chrono::steady_clock::time_point start1 = std::chrono::steady_clock::now();
sleep(5s); // sleep for 5 seconds
std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now();
std::cout << std::setprecision(9) << std::fixed;
std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::seconds>(end1-start1).count() << "s\n";
std::chrono::steady_clock::time_point start2 = std::chrono::steady_clock::now();
sleep(500000ns); // sleep for 500000 nano seconds/500 micro seconds
// same as writing: sleep(500us)
std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();
std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count() << "us\n";
return 0;
}
For more information, visit https://en.cppreference.com/w/cpp/header/chrono
and see this cppcon talk of Howard Hinnant, https://www.youtube.com/watch?v=P32hvk8b13M.
He has two more talks on chrono library. And you can always use the library function, std::this_thread::sleep_for
Note: Outputs may not be accurate. So, don't expect it to give exact timings.
Active 1st tab
$("#workflowTab").tabs({ active: 0 });
Active last tab
$("#workflowTab").tabs({ active: -1 });
Active 2nd tab
$("#workflowTab").tabs({ active: 1 });
Its work like an array
In my case i have a main.py that have dependencies with other files. After I build that app with py installer using this command:
pyinstaller --onefile --windowed main.py
I got the main.exe inside dist folder. I double clicked on this file, and I raised the error mentioned above. To fix this, I just copy the main.exe from dist directory to previous directory, which is the root directory of my main.py and the dependency files, and I got no error after run the main.exe.
Here is what I use
$textToStore = nl2br(htmlentities($inputText, ENT_QUOTES, 'UTF-8'));
$inputText
is the text provided by either the form or textarea.
$textToStore
is the returned text from nl2br
and htmlentities
, to be stored in your database.
ENT_QUOTES
will convert both double and single quotes, so you'll have no trouble with those.
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Try this,
I think ,this is one of the simple solutions.
int rowIndex = table.Rows.IndexOf(table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'")[0]);
string strD= Convert.ToString(table.Rows[rowIndex]["D"]);
Make sure,combination of values for column A, B and C is unique in the datatable.
All the above answers are correct. Just providing with your dataset to find perfect divisor:
#include <stdio.h>
int main()
{
int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;
for (i=0 ; i < 7; i++) {
if (j % arr[i] == 0)
printf("%d is the perfect divisor of %d\n", arr[i], j);
}
return 0;
}
The lingo in excel is different, you don't "declare variables", you "name" cells or arrays.
A good overview of how you do that is below: http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010342417.aspx
I created a React component for this specific case: https://github.com/coreyleelarson/react-typekit
Just need to pass in your Typekit Kit ID as a prop and you're good to go.
import React from 'react';
import Typekit from 'react-typekit';
const HtmlLayout = () => (
<html>
<body>
<h1>My Example React Component</h1>
<Typekit kitId="abc123" />
</body>
</html>
);
export default HtmlLayout;
The Swift equivalent to NSMutableArray
's removeObject
is:
var array = ["alpha", "beta", "gamma"]
if let index = array.firstIndex(of: "beta") {
array.remove(at: index)
}
if the objects are unique. There is no need at all to cast to NSArray
and use indexOfObject:
The API index(of:
also works but this causes an unnecessary implicit bridge cast to NSArray
.
If there are multiple occurrences of the same object use filter
. However in cases like data source arrays where an index is associated with a particular object firstIndex(of
is preferable because it's faster than filter
.
Update:
In Swift 4.2+ you can remove one or multiple occurrences of beta
with removeAll(where:)
:
array.removeAll{$0 == "beta"}
The underlying problem is Ctrl+Alt+Left and Right are used by window managers to switch workspace and/or OEM utilities to change the screen orientation.
You can change the assignments using
File / Settings / Keymap
then Main Menu / Navigate
find Back
and Forward
and right click to Add Keyboard Shortcut
to set an alternative key chord.
Alt Graph+Left and Alt Graph+Right works well for me (IDEA 13.1.4 on Ubuntu under IceWM).
You first need to understand Call Stack. Understanding Call stack will also give you clarity to how "function hierarchy and execution order" works in JavaScript Engine.
The call stack is primarily used for function invocation (call). Since there is only one call stack. Hence, all function(s) execution get pushed and popped one at a time, from top to bottom.
It means the call stack is synchronous. When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. So, basically if everything is running smooth, then at the very beginning and at the end, Call Stack will be found empty.
Here is the illustration of Call Stack:
Now, if you provide too many arguments or caught inside any unhandled recursive call. You will encounter
RangeError: Maximum call stack size exceeded
which is quite obvious as explained by others.
Hope this helps !
Use the svn export
command:
cd c:\websites\test
svn export c:\websites\test_copy
All files under version control will be exported. Double check to make sure you haven't missed anything.
According to Microsoft's documentation
On the Tools menu, point to Macro, and then click Macros.
In the Macro name box, enter the name of the macro you want to assign to a keyboard shortcut key.
Click Options.
If you want to run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box. You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters), where letter is any letter key on the keyboard. The shortcut key cannot use a number or special character, such as @
or #
.
Note: The shortcut key will override any equivalent default Microsoft Excel shortcut keys while the workbook that contains the macro is open.
If you want to include a description of the macro, type it in the Description box.
Click OK.
Click Cancel.
To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too
>>> greek=u"aß?de??????µ???p??st?f???"
>>> print len(greek)
25
>>> print greek[:10]
aß?de?????
If you want to run the above code as a script, put this line at the top
# -*- coding: utf-8 -*-
If your editor doesn't save in utf-8, substitute the correct encoding
You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.
It's kind of hard to tell in your exact situation but I'd probably use a v-for
and make an array of finds
to push to as I need more.
Here's how I'd set up my instance:
new Vue({
el: '#app',
data: {
finds: []
},
methods: {
addFind: function () {
this.finds.push({ value: '' });
}
}
});
And here's how I'd set up my template:
<div id="app">
<h1>Finds</h1>
<div v-for="(find, index) in finds">
<input v-model="find.value" :key="index">
</div>
<button @click="addFind">
New Find
</button>
</div>
Although, I'd try to use something besides an index
for the key
.
Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/
When stuck on Visual Studio Preparation:
I killed vs_enterprise.exe with higher PID, Visual Studio threw an error, that "pipe is being closed". Restarted PC & Logged in. Visual Studio started automatically and has completed within 1 minute.
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf
and postgres.conf
files I finally found out that my firewall was overriding everything and therefore blocking connections
Other solutions mix regex syntaxes. To use perl/PCRE patterns for both search and replace, and only process matching files, this works quite well:
grep -rlIZPi 'match1' | xargs -0r perl -pi -e 's/match2/replace/gi;'
match1
and match2
are usually identical but match1
can be simplified to remove more advanced features that are only relevant to the substitution, e.g. capturing groups.
Translation: grep
recursively and list matching filenames, each separated by nul to protect any special characters; pipe any filenames to xargs
which is expecting a nul-separated list; if any filenames are received, pass them to perl
to perform the actual substitutions.
For case-sensitive matching, drop the i
flag from grep
and the i
pattern modifier from the s///
expression, but not the i
flag from perl
itself. Remove the I
flag from grep
to include binary files.
1) Check the CodeFile property in <%@Page CodeFile="filename.aspx.cs" %> in "filename.aspx" page , your Code behind file name and this Property name should be same.
2)you may miss runat="server" in code
Try wrapping the list in a div and give that div the inline property instead of your list.
def word_in(s):
return " " not in s
If your iPhone is jailbroken you can use DemoGod
File names under OS X are not case sensitive (by default). This is more of an OS problem than a Git problem. If you remove and readd the file, you should get what you want, or rename it to something else and then rename it back.
Switch to the branch from which you created the pull request:
$ git checkout pull-request-branch
Overwrite the modified file(s) with the file in another branch, let's consider it's master:
git checkout origin/master -- src/main/java/HelloWorld.java
Commit and push it to the remote:
git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch
In my case, the problem was I used wrong alias for git commit -m
. I used gc
alias which dit not meant git commit -m
You might want to try int.TryParse(string, out int)
in the KeyPress(object, KeyPressEventArgs)
event to check for numeric values. For the other problem you could use regular expressions instead.
I did:
$git pull origin master
Then it asked for the [Username] & [Password] and it seems to be working fine now.
I’ve made a small gem that can alleviate the need to manually delete associated records in some circumstances.
This gem adds a new option for ActiveRecord associations:
dependent: :delete_recursively
When you destroy a record, all records that are associated using this option will be deleted recursively (i.e. across models), without instantiating any of them.
Note that, just like dependent: :delete or dependent: :delete_all, this new option does not trigger the around/before/after_destroy callbacks of the dependent records.
However, it is possible to have dependent: :destroy associations anywhere within a chain of models that are otherwise associated with dependent: :delete_recursively. The :destroy option will work normally anywhere up or down the line, instantiating and destroying all relevant records and thus also triggering their callbacks.
In Chrome it's possible to hide this automatic header/footer using
@page { margin: 0; }
Since the contents will extend to page's limits, the page printing header/footer will be absent. You should, of course, in this case, set some margins/paddings in your body element so that the content won't extend all the way to the page's edge. Since common printers just can't get no-margins printing and it's probably not what you want, you should use something like this:
@media print {
@page { margin: 0; }
body { margin: 1.6cm; }
}
As Martin pointed out in a comment, if the page have a long element that scrolls past one page (like a big table), the margin is ignored and the printed version will look weird.
At the time original of this answer (May 2013), it only worked on Chrome, not sure about it now, never needed to try again. If you need support for a browser that can't hable, you can create a PDF on the fly and print that (you can create a self-printing PDF embedding JavaScript on it), but that's a huge hassle.
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
Database Connection:
try {
$conn = mysqli_connect($servername, $username, $password, $db);
//echo "Connected successfully";
} catch (exception $e) {
echo "Connection failed: " . $e->getMessage();
}
Code to read CSV file and upload to table in database.
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
$sql = "INSERT into db_table
values ('','" . $getData[1] . "','" . $getData[2] . "','" . $getData[3] . "','" . $getData[4] . "','" . $getData[5] . "','" . $getData[6] . "')";
$result = mysqli_query($conn, $sql);
if (!isset($result)) {
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.
window.location = \"home.do\"
</script>";
} else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"home.do\"
</script>";
}
}
fclose($file);
Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serializeArray();
var formData = JSON.stringify(criteria);
serializeArray() will produce an array of names and values
0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serialize();
serialize() creates a text string in standard URL-encoded notation
"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"
If you are using Appcompact
Activity use these three lines in your theme.
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowActionBarOverlay">false</item>
It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries) . So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.
For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,
<input my-directive value="{{1+1}}">
use Attributes' method $observe
:
myApp.directive('myDirective', function () {
return function (scope, element, attr) {
attr.$observe('value', function(actual_value) {
element.val("value = "+ actual_value);
})
}
});
From the directive page,
observing interpolated attributes: Use
$observe
to observe the value changes of attributes that contain interpolation (e.g.src="{{bar}}"
). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set toundefined
.
If the attribute value is just a constant, e.g.,
<input my-directive value="123">
you can use $eval if the value is a number or boolean, and you want the correct type:
return function (scope, element, attr) {
var number = scope.$eval(attr.value);
console.log(number, number + 1);
});
If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:
return function (scope, element, attr) {
var str = attr.value;
console.log(str, str + " more");
});
In your case, however, since you want to support interpolated values and constants, use $observe
.
Corrected;
/*
return true if the array is not empty
return false if it is empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr as $key => $value){
if(!empty($value) || $value != NULL || $value != ""){
return true;
break;//stop the process we have seen that at least 1 of the array has value so its not empty
}
}
return false;
}
}
The simulators are located under:
~/Library/Developer/CoreSimulator/
Here, they are listed as directories with UUID names. Use sort by 'Date modified' to find the latest one. Inside navigate to:
/data/Containers/Data/Application/
Here you will get a list of all the applications on that device. You can again sort this to get the latest app.
NOTE: Xcode changes the directory name every time you run the app, so don't rely on making alias/short cuts on desktop.
The easiest way is to use the app here, which does everything automatically.
Using DISTINCT should do it:
SELECT DISTINCT id, uname, tel
FROM YourTable
Though you could really do with having a primary key on that table, a way to uniquely identify each record. I'd be considering sticking an IDENTITY column on the table
Since Apple released iTunes 12, you must use Apple Configurator 2 app to install ipa in your iPhone and iPad.
Download from this link: https://itunes.apple.com/br/app/apple-configurator-2/id1037126344?mt=12
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.
var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}
var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}
So, do not convert to set if you have repeated values in your array.
You are scanning the wrong package:
@ComponentScan("**org**.pharmacy")
Where as it should be:
@ComponentScan("**com**.pharmacy")
Since your package names start with com and not org.
Pull from the repository to a new directory, then rename the old one to old_crufty
, and the new one to my_real_webserver_directory
, and you're good to go.
If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.
And using ports:
port install gradle
Ports , tested on El Capitan
All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.
For example:
private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
return;
MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());
}
This works for me in Ubuntu 12.04 and 15.10
if pip not installed:
sudo apt-get install python-pip
and then:
sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2
This works for me.
<div style="position: relative;width:100%;">
<div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
This will be on the left
</div>
<div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
This will be on the right
</div>
</div>
<?php
$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];
if($browser_ver['browser'] == 'IE') {
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id) {
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>
<body style="margin:0; height:100%;">
<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>
</body>
</html>
<?php
} else {
?>
<HTML>
<script Language="javascript">
function printfile(id) {
window.frames[id].focus();
window.frames[id].print();
}
</script>
<BODY marginheight="0" marginwidth="0">
<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>
<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">
</BODY>
</HTML>
<?php
}
?>
#!/bin/bash -e
x='2018-01-18 10:00:00'
a=$(date -d "$x")
b=$(date -d "$a 10 min" "+%Y-%m-%d %H:%M:%S")
c=$(date -d "$b 10 min" "+%Y-%m-%d %H:%M:%S")
#date -d "$a 30 min" "+%Y-%m-%d %H:%M:%S"
echo Entered Date is $x
echo Second Date is $b
echo Third Date is $c
Here x is sample date used & then example displays both formatting of data as well as getting dates 10 mins more then current date.
I frankly would recommend the RazorGenerator nuget package. That way your views have a .designer.cs
file generated when you save them and on top of getting compile time errors for you views, they are also precompiled into the assembly (= faster warmup) and Resharper provides some additional help as well.
To use this include the RazorGenerator nuget package in you ASP.NET MVC project and install the "Razor Generator" extension under item under Tools ? Extensions and Updates.
We use this and the overhead per compile with this approach is much less. On top of this I would probably recommend .NET Demon by RedGate which further reduces compile time impact substantially.
Hope this helps.
It is a reference to the current file name. In the file foo.rb
, __FILE__
would be interpreted as "foo.rb"
.
Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:
# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__
Running ruby test.rb
will output
test.rb
/full/path/to/dir2/test.rb
I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32
If you can live with limited parallel capablilities, the following solution will work:
private static <T> Stream<T> nonEmptyStream(
Stream<T> stream, Supplier<RuntimeException> e) {
Spliterator<T> it=stream.spliterator();
return StreamSupport.stream(new Spliterator<T>() {
boolean seen;
public boolean tryAdvance(Consumer<? super T> action) {
boolean r=it.tryAdvance(action);
if(!seen && !r) throw e.get();
seen=true;
return r;
}
public Spliterator<T> trySplit() { return null; }
public long estimateSize() { return it.estimateSize(); }
public int characteristics() { return it.characteristics(); }
}, false);
}
Here is some example code using it:
List<String> l=Arrays.asList("hello", "world");
nonEmptyStream(l.stream(), ()->new RuntimeException("No strings available"))
.forEach(System.out::println);
nonEmptyStream(l.stream().filter(s->s.startsWith("x")),
()->new RuntimeException("No strings available"))
.forEach(System.out::println);
The problem with (efficient) parallel execution is that supporting splitting of the Spliterator
requires a thread-safe way to notice whether either of the fragments has seen any value in a thread-safe manner. Then the last of the fragments executing tryAdvance
has to realize that it is the last one (and it also couldn’t advance) to throw the appropriate exception. So I didn’t add support for splitting here.
You get an apparently random set because ROWNUM is applied before the ORDER BY. So your query takes the first ten rows and sorts them.0 To select the top ten salaries you should use an analytic function in a subquery, then filter that:
select * from
(select empno,
ename,
sal,
row_number() over(order by sal desc nulls last) rnm
from emp)
where rnm<=10
To add one more item to Spinner you can:
ArrayAdapter myAdapter =
((ArrayAdapter) mySpinner.getAdapter());
myAdapter.add(myValue);
myAdapter.notifyDataSetChanged();
Please check whether another mysql service is running.
One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline
functions from output by default, but will keep plain static
functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline
for static
functions in headers.
document.getElementById("demo").innerHTML = voteable
finds the element with the id demo and then places the voteable
value into it; either too young or old enough.
So effectively <p id="demo"></p>
becomes for example <p id="demo">Old Enough</p>
Here is what works for me.
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in your manifest and the code below
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Your syntax is wrong.
You need to call attr
with two parameters, like this:
$('.salesperson', newOption).attr('defaultSelected', "selected");
Your current code assigns the value "selected"
to the variable defaultSelected
, then passes that value to the attr
function, which will then return the value of the selected
attribute.
Here's how to get the transcript of a YouTube video (when available):
Although the syntax may be a little goofy this is a pretty good solution.
Source: http://ccm.net/faq/40644-youtube-how-to-get-the-transcript-of-a-video
You can't. I think you have FOUR options here. All four offer a solution but with a slightly different approach...
Option One: use the built-in name()
on an enum. This is perfectly fine if you don't need any special naming format.
String name = Modes.mode1.name(); // Returns the name of this enum constant, exactly as declared in its enum declaration.
Option Two: add overriding properties to your enums if you want more control
public enum Modes {
mode1 ("Fancy Mode 1"),
mode2 ("Fancy Mode 2"),
mode3 ("Fancy Mode 3");
private final String name;
private Modes(String s) {
name = s;
}
public boolean equalsName(String otherName) {
// (otherName == null) check is not needed because name.equals(null) returns false
return name.equals(otherName);
}
public String toString() {
return this.name;
}
}
Option Three: use static finals instead of enums:
public final class Modes {
public static final String MODE_1 = "Fancy Mode 1";
public static final String MODE_2 = "Fancy Mode 2";
public static final String MODE_3 = "Fancy Mode 3";
private Modes() { }
}
Option Four: interfaces have every field public, static and final:
public interface Modes {
String MODE_1 = "Fancy Mode 1";
String MODE_2 = "Fancy Mode 2";
String MODE_3 = "Fancy Mode 3";
}
A simplest fix would be:
x = input("Give starting number: ")
y = input("Give ending number: ")
x = int(x) # parse string into an integer
y = int(y) # parse string into an integer
for i in range(x,y):
print(i)
input
returns you a string (raw_input
in Python 2). int
tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try
/except
statements.
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
If you don't like split()
and you don't mind NAs padding out your short tail:
chunk <- function(x, n) { if((length(x)%%n)==0) {return(matrix(x, nrow=n))} else {return(matrix(append(x, rep(NA, n-(length(x)%%n))), nrow=n))} }
The columns of the returned matrix ([,1:ncol]) are the droids you are looking for.
Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.
Here is the link
I wouldn't have thought so.
If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.
If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!
Had to do something similar, hope this helps.
// Node packages for file system
var fs = require('fs');
var path = require('path');
var filePath = path.join(__dirname, 'PATH_TO_CSV');
// Read CSV
var f = fs.readFileSync(filePath, {encoding: 'utf-8'},
function(err){console.log(err);});
// Split on row
f = f.split("\n");
// Get first row for column headers
headers = f.shift().split(",");
var json = [];
f.forEach(function(d){
// Loop through each row
tmp = {}
row = d.split(",")
for(var i = 0; i < headers.length; i++){
tmp[headers[i]] = row[i];
}
// Add object to list
json.push(tmp);
});
var outPath = path.join(__dirname, 'PATH_TO_JSON');
// Convert object to string, write json to file
fs.writeFileSync(outPath, JSON.stringify(json), 'utf8',
function(err){console.log(err);});
<br/>
as normal, but hide it with display: none
when you don't want it.I would expect most people finding this question want to use css / responsive design to decide whether or not a line-break appears in a specific place. (and don't have anything personal against <br/>
)
While not immediately obvious, you can actually apply display:none
to a <br/>
tag to hide it, which enables the use of media queries in tandem with semantic BR tags.
<div>
The quick brown fox<br />
jumps over the lazy dog
</div>
@media screen and (min-width: 20em) {
br {
display: none; /* hide the BR tag for wider screens (i.e. disable the line break) */
}
}
This is useful in responsive design where you need to force text into two lines at an exact break.
Eclipse Oxygen - after installation of Lombok according to the process described on the Lombok page, still could not use @Log annotation.
Solution : Project --> Properties - Enable annotation processing
The behaviour differs depending on whether the target file name already exists or not. It's usually a safety mechanism, and there are at least 3 different cases:
In this case svn mv
should work as follows:
$ svn mv old_file_name new_file_name
A new_file_name
D old_file_name
$ svn stat
A + new_file_name
> moved from old_file_name
D old_file_name
> moved to new_file_name
$ svn commit
Adding new_file_name
Deleting old_file_name
Committing transaction...
In this case, the target file needs to be removed explicitly, before the source file can be renamed. This can be done in the same transaction as follows:
$ svn mv old_file_name new_file_name
svn: E155010: Path 'new_file_name' is not a directory
$ svn rm new_file_name
D new_file_name
$ svn mv old_file_name new_file_name
A new_file_name
D old_file_name
$ svn stat
R + new_file_name
> moved from old_file_name
D old_file_name
> moved to new_file_name
$ svn commit
Replacing new_file_name
Deleting old_file_name
Committing transaction...
In the output of svn stat
, the R
indicates that the file has been replaced, and that the file has a history.
In this case, the content of the local file would be lost. If that's okay, then the file can be removed locally before renaming the existing file.
$ svn mv old_file_name new_file_name
svn: E155010: Path 'new_file_name' is not a directory
$ rm new_file_name
$ svn mv old_file_name new_file_name
A new_file_name
D old_file_name
$ svn stat
A + new_file_name
> moved from old_file_name
D old_file_name
> moved to new_file_name
$ svn commit
Adding new_file_name
Deleting old_file_name
Committing transaction...
Fiddle of my solution is here. But just in case it expires I will paste the code as well.
HTML:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />
JS:
var sel = document.getElementById('sel'),
button = document.getElementById('button');
button.addEventListener('click', function (e) {
sel.options[1].selected = true;
// firing the event properly according to StackOverflow
// http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
sel.dispatchEvent(evt);
}
else {
sel.fireEvent("onchange");
}
});
sel.addEventListener('change', function (e) {
alert('changed');
});
You can also map the share to a local drive as follows:
net use X: "\\servername\share" /user:morgan password
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
There are changes in mongod.conf file in the latest MongoDB v 3.6.5 +
Here is how I fixed this issue on mac os High Sierra v 10.12.3
Note: I assume that you have installed/upgrade MongoDB using homebrew
mongo --version
MongoDB shell version v3.6.5
git version: a20ecd3e3a174162052ff99913bc2ca9a839d618
OpenSSL version: OpenSSL 1.0.2o 27 Mar 2018
allocator: system modules: none build environment:
distarch: x86_64
target_arch: x86_64
find mongod.conf file
sudo find / -name mongod.conf`
/usr/local/etc/mongod.conf > first result .
open mongod.conf file
sudo vi /usr/local/etc/mongod.conf
edit in the file for remote access under net: section
port: 27017
bindIpAll: true
#bindIp: 127.0.0.1 // comment this out
restart mongodb
if you have installed using brew than
brew services stop mongodb
brew services start mongodb
otherwise, kill the process.
sudo kill -9 <procssID>
Yes, it's indeed a sad fact that keytool has no functionality to import a private key.
For the record, at the end I went with the solution described here
"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.
You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.
If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...
Example..
Month varchar2(3) --Month code in Alpha..
Year NUMBER -- Year in number
or
Month number(2) --Month Number in Year.
Year NUMBER -- Year in number
in our use we have to capture with host x.x.x.x. or (vlan and host x.x.x.x)
anything less will not capture? I am not sure why but that is the way it works!
I have created a data frame in a for loop with the help of a temporary empty data frame. Because for every iteration of for loop, a new data frame will be created thereby overwriting the contents of previous iteration.
Hence I need to move the contents of the data frame to the empty data frame that was created already. It's as simple as that. We just need to use .append function as shown below :
temp_df = pd.DataFrame() #Temporary empty dataframe
for sent in Sentences:
New_df = pd.DataFrame({'words': sent.words}) #Creates a new dataframe and contains tokenized words of input sentences
temp_df = temp_df.append(New_df, ignore_index=True) #Moving the contents of newly created dataframe to the temporary dataframe
Outside the for loop, you can copy the contents of the temporary data frame into the master data frame and then delete the temporary data frame if you don't need it
public class SwitCase {
public static void main (String[] args){
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); //get the first char.
switch(hi){
case 'a': System.out.println("a");
}
}
}
I suggest an improvement of the Adam's answer accepting HashMap as parameter
/**
* Append parameters to given url
* @param url
* @param parameters
* @return new String url with given parameters
* @throws URISyntaxException
*/
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
URI uri = new URI(url);
String query = uri.getQuery();
StringBuilder builder = new StringBuilder();
if (query != null)
builder.append(query);
for (Map.Entry<String, String> entry: parameters.entrySet())
{
String keyValueParam = entry.getKey() + "=" + entry.getValue();
if (!builder.toString().isEmpty())
builder.append("&");
builder.append(keyValueParam);
}
URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
return newUri.toString();
}
I have written a beautiful, nested select. Maybe it will help you.
https://jsfiddle.net/nomorepls/tg13w5r7/1/
function on_change_select(e) {
alert(e.value, e.title, e.option, e.select);
}
$(document).ready(() => {
// NESTED SELECT
$(document).on('click', '.nested-cell', function() {
$(this).next('div').toggle('medium');
});
$(document).on('change', 'input[name="nested-select-hidden-radio"]', function() {
const parent = $(this).closest(".nested-select");
const value = $(this).attr('value');
const title = $(this).attr('title');
const executer = parent.attr('executer');
if (executer) {
const event = new Object();
event.value = value;
event.title = title;
event.option = $(this);
event.select = parent;
window[executer].apply(null, [event]);
}
parent.attr('value', value);
parent.parent().slideToggle();
const button = parent.parent().prev();
button.toggleClass('active');
button.addClass('selected');
button.children('.nested-select-title').html(title);
});
$(document).on('click', '.nested-select-button', function() {
const button = $(this);
let select = button.parent().children('.nested-select-wrapper');
if (!button.hasClass('active')) {
select = select.detach();
if (button.height() + button.offset().top + $(window).height() * 0.4 > $(window).height()) {
select.insertBefore(button);
select.css('margin-top', '-44vh');
select.css('top', '0');
} else {
select.insertAfter(button);
select.css('margin-top', '');
select.css('top', '40px');
}
}
select.slideToggle();
button.toggleClass('active');
});
});
_x000D_
.container {
width: 200px;
position: relative;
top: 0;
left: 0;
right: 0;
height: auto;
}
.nested-select-box {
font-family: Arial, Helvetica, sans-serif;
display: block;
position: relative;
width: 100%;
height: fit-content;
cursor: pointer;
color: #2196f3;
height: 40px;
font-size: small;
/* z-index: 2000; */
}
.nested-select-box .nested-select-button {
border: 1px solid #2196f3;
position: absolute;
width: calc(100% - 20px);
padding: 0 10px;
min-height: 40px;
word-wrap: break-word;
margin: 0 auto;
overflow: hidden;
}
.nested-select-box.danger .nested-select-button {
border: 1px solid rgba(250, 33, 33, 0.678);
}
.nested-select-box .nested-select-button .nested-select-title {
padding-right: 25px;
padding-left: 25px;
width: calc(100% - 50px);
margin: auto;
height: fit-content;
text-align: center;
vertical-align: middle;
position: absolute;
top: 0;
bottom: 0;
left: 0;
}
.nested-select-box .nested-select-button.selected .nested-select-title {
bottom: unset;
top: 5px;
}
.nested-select-box .nested-select-button .nested-select-title-icon {
position: absolute;
height: 20px;
width: 20px;
top: 10px;
bottom: 10px;
right: 7px;
transition: all 0.5s ease 0s;
}
.nested-select-box .nested-select-button.active .nested-select-title-icon {
-moz-transform: scale(-1, -1);
-o-transform: scale(-1, -1);
-webkit-transform: scale(-1, -1);
transform: scale(-1, -1);
}
.nested-select-box .nested-select-button .nested-select-title-icon::before,
.nested-select-box .nested-select-button .nested-select-title-icon::after {
content: "";
background-color: #2196f3;
position: absolute;
width: 70%;
height: 2px;
transition: all 0.5s ease 0s;
top: 9px;
}
.nested-select-box .nested-select-button .nested-select-title-icon::before {
transform: rotate(45deg);
left: -1.6px;
}
.nested-select-box .nested-select-button .nested-select-title-icon::after {
transform: rotate(-45deg);
left: 7px;
}
.nested-select-box .nested-select-wrapper {
width: 100%;
top: 40px;
position: relative;
border: 1px solid #2196f3;
background: #ffffff;
z-index: 2005;
opacity: 1;
}
.nested-select {
font-family: Arial, Helvetica, sans-serif;
display: inline-block;
overflow-y: scroll;
max-height: 40vh;
width: calc(100% - 10px);
padding: 5px;
-ms-overflow-style: none;
scrollbar-width: none;
}
.nested-select::-webkit-scrollbar {
display: none;
}
.nested-select a,
.nested-select span {
padding: 0 5px;
border-radius: 3px;
cursor: pointer;
text-align: start;
}
.nested-select a:hover {
background-color: #62b2f3;
color: #ffffff;
}
.nested-select span:hover {
background-color: #c4c4c4;
color: #ffffff;
}
.nested-select input[type="radio"] {
display: none;
}
.nested-select input[type="radio"]+span {
display: block;
}
.nested-select input[type="radio"]:checked+span {
background-color: #2196f3;
color: #ffffff;
}
.nested-select div {
margin-left: 15px;
}
.nested-select label>span:before,
.nested-select a:before {
content: "\2022";
margin-right: 5px;
}
.nested-select a {
display: block;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="nested-select-box w-100">
<div class="nested-select-button">
<p class="nested-select-title">
Account
</p>
<span class="nested-select-title-icon"></span>
</div>
<div class="nested-select-wrapper" style="display: none;">
<div class="nested-select" executer="on_change_select">
<label>
<input title="Accounting and legal services" value="1565142000000891539" type="radio" name="nested-select-hidden-radio">
<span>Accounting and legal services</span>
</label>
<label>
<input title="Advertising agencies" value="1565142000000891341" type="radio" name="nested-select-hidden-radio">
<span>Advertising agencies</span>
</label>
<a class="nested-cell">Advertising And Marketing</a>
<div>
<label>
<input title="Advertising agencies" value="1565142000000891341" type="radio" name="nested-select-hidden-radio">
<span>Advertising agencies</span>
</label>
<a class="nested-cell">Adwords - traffic</a>
<div>
<label>
<input title="Adwords - traffic: Charters and general search" value="1565142000003929177" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Charters and general search</span>
</label>
<label>
<input title="Adwords - traffic: Distance course" value="1565142000007821291" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Distance course</span>
</label>
<label>
<input title="Adwords - traffic: Events" value="1565142000003929189" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Events</span>
</label>
<label>
<input title="Adwords - traffic: Practices" value="1565142000003929165" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Practices</span>
</label>
<label>
<input title="Adwords - traffic: Sailing tours" value="1565142000003929183" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Sailing tours</span>
</label>
<label>
<input title="Adwords - traffic: Theoretical courses" value="1565142000003929171" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Theoretical courses</span>
</label>
</div>
<label>
<input title="Branded products" value="1565142000000891533" type="radio" name="nested-select-hidden-radio">
<span>Branded products</span>
</label>
<label>
<input title="Business cards" value="1565142000005438323" type="radio" name="nested-select-hidden-radio">
<span>Business cards</span>
</label>
<a class="nested-cell">Facebook, Instagram - traffic</a>
<div>
<label>
<input title="Facebook, Instagram - traffic: Charters and general search" value="1565142000003929145" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Charters and general search</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Distance course" value="1565142000007821285" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Distance course</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Events" value="1565142000003929157" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Events</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Practices" value="1565142000003929133" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Practices</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Sailing tours" value="1565142000003929151" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Sailing tours</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Theoretical courses" value="1565142000003929139" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Theoretical courses</span>
</label>
</div>
<label>
<input title="Offline Advertising (posters, banners, partnerships)" value="1565142000000891377" type="radio" name="nested-select-hidden-radio">
<span>Offline Advertising (posters, banners, partnerships)</span>
</label>
<label>
<input title="Photos, video etc." value="1565142000000891371" type="radio" name="nested-select-hidden-radio">
<span>Photos, video etc.</span>
</label>
<label>
<input title="Prize fund" value="1565142000001404931" type="radio" name="nested-select-hidden-radio">
<span>Prize fund</span>
</label>
<label>
<input title="SEO" value="1565142000000891365" type="radio" name="nested-select-hidden-radio">
<span>SEO</span>
</label>
<label>
<input title="SMM Content creation (texts, copywriting)" value="1565142000000891389" type="radio" name="nested-select-hidden-radio">
<span>SMM Content creation (texts, copywriting)</span>
</label>
<a class="nested-cell">YouTube</a>
<div>
<label>
<input title="YouTube: travel expenses" value="1565142000008100163" type="radio" name="nested-select-hidden-radio">
<span>YouTube: travel expenses</span>
</label>
<label>
<input title="Youtube: video editing" value="1565142000008100157" type="radio" name="nested-select-hidden-radio">
<span>Youtube: video editing</span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
_x000D_
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
Yes, a struct
is identical to a class
except for the default access level (member-wise and inheritance-wise). (and the extra meaning class
carries when used with a template)
Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.
struct foo {
int bar;
foo() : bar(3) {} //look, a constructor
int getBar()
{
return bar;
}
};
foo f;
int y = f.getBar(); // y is 3
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.
2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).
Say you have a table containing courses that are taken in a certain semester, and you have the following data:
|-----Primary Key----| uh oh |
V
CourseID | SemesterID | #Places | Course Name |
------------------------------------------------|
IT101 | 2009-1 | 100 | Programming |
IT101 | 2009-2 | 100 | Programming |
IT102 | 2009-1 | 200 | Databases |
IT102 | 2010-1 | 150 | Databases |
IT103 | 2009-2 | 120 | Web Design |
This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.
Primary Key |
CourseID | Course Name |
---------------------------|
IT101 | Programming |
IT102 | Databases |
IT103 | Web Design |
No redundancy!
Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:
|-----Primary Key----| uh oh |
V
Course | Semester | #Places | TeacherID | TeacherName |
---------------------------------------------------------------|
IT101 | 2009-1 | 100 | 332 | Mr Jones |
IT101 | 2009-2 | 100 | 332 | Mr Jones |
IT102 | 2009-1 | 200 | 495 | Mr Bentley |
IT102 | 2010-1 | 150 | 332 | Mr Jones |
IT103 | 2009-2 | 120 | 242 | Mrs Smith |
Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.
Primary Key |
TeacherID | TeacherName |
---------------------------|
332 | Mr Jones |
495 | Mr Bentley |
242 | Mrs Smith |
No redundancy!!
One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.
You can use swift.quicktype.io for converting JSON
to either struct
or class
. Even you can mention version of swift to genrate code.
Example JSON:
{
"message": "Hello, World!"
}
Generated code:
import Foundation
typealias Sample = OtherSample
struct OtherSample: Codable {
let message: String
}
// Serialization extensions
extension OtherSample {
static func from(json: String, using encoding: String.Encoding = .utf8) -> OtherSample? {
guard let data = json.data(using: encoding) else { return nil }
return OtherSample.from(data: data)
}
static func from(data: Data) -> OtherSample? {
let decoder = JSONDecoder()
return try? decoder.decode(OtherSample.self, from: data)
}
var jsonData: Data? {
let encoder = JSONEncoder()
return try? encoder.encode(self)
}
var jsonString: String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
}
extension OtherSample {
enum CodingKeys: String, CodingKey {
case message
}
}
USE this sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
Android Studio fails to build new project, timed out while wating for slave aapt process
The first problem is that button1
is a local variable of the main
method, so the actionPerformed
method doesn't have access to it.
The second problem is that the ActionListener
interface is implemented by the class calc
, but no instance of this class is created in the main
method.
The usual way to do what you want is to create an instance of calc
and make button1
a field of the calc
class.
Metrics and Svens answer deals with the usual situation but for us who work in non-english enviroments if you have exotic characters (å,ä,ö) in your character variable you will get the same result, even if you have multiple factor levels.
Levels <- c("Pri", "För")
gives the contrast error, while Levels <- c("Pri", "For")
doesn't
This is probably a bug.
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
One way you can perform this operation for all the values 1 through 7 at once is to use the function ACCUMARRAY:
>> M = randi(7,1500,1); %# Some random sample data with the values 1 through 7
>> dayCounts = accumarray(M,1) %# Will return a 7-by-1 vector
dayCounts =
218 %# Number of Sundays
200 %# Number of Mondays
213 %# Number of Tuesdays
220 %# Number of Wednesdays
234 %# Number of Thursdays
219 %# Number of Fridays
196 %# Number of Saturdays
You need to quote that filename:
f = open("D\\python\\HW\\2_1 - Copy.cp", "r")
Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:
print "This is a long",\
"line of text",\
"that I'm printing."
Also, you shouldn't have semicolons (;
) at the end of your statements in Python.
The shortest one I could come up with is:
chmod -R a=r,u+w,a+X /foo
which works on GNU/Linux, and I believe on Posix in general (from my reading of: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/chmod.html).
What this does is:
Importantly, the step 1 permission clears all execute bits, so step 3 only adds back execute bits for directories (never files). In addition, all three steps happen before a directory is recursed into (so this is not equivalent to e.g.
chmod -R a=r /foo
chmod -R u+w /foo
chmod -R a+X /foo
since the a=r removes x from directories, so then chmod can't recurse into them.)
In case anyone looking for latest Swift version then below code is working fine with Xcode 10.2 and Swift 4.2
yourTextView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
You are missing the view engine, for example use jade:
change your
app.set('view engine', 'html');
with
app.set('view engine', 'jade');
If you want use a html friendly syntax use instead ejs
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
EDIT
As you can read from view.js Express View Module
module.exports = View;
/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* @param {String} name
* @param {Object} options
* @api private
*/
function View(name, options) {
options = options || {};
this.name = name;
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
}
You must have installed a default engine
Express
search default layout view by program.template
as you can read below:
mkdir(path + '/views', function(){
switch (program.template) {
case 'ejs':
write(path + '/views/index.ejs', ejsIndex);
break;
case 'jade':
write(path + '/views/layout.jade', jadeLayout);
write(path + '/views/index.jade', jadeIndex);
break;
case 'jshtml':
write(path + '/views/layout.jshtml', jshtmlLayout);
write(path + '/views/index.jshtml', jshtmlIndex);
break;
case 'hjs':
write(path + '/views/index.hjs', hoganIndex);
break;
}
});
and as you can read below:
program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';
the default view engine is jade
Use the PowerConsole project on Github at https://github.com/bigabdoul/PowerConsole or the equivalent NuGet package at https://www.nuget.org/packages/PowerConsole. It elegantly handles timers in a reusable fashion. Take a look at this sample code:
using PowerConsole;
namespace PowerConsoleTest
{
class Program
{
static readonly SmartConsole MyConsole = SmartConsole.Default;
static void Main()
{
RunTimers();
}
public static void RunTimers()
{
// CAUTION: SmartConsole is not thread safe!
// Spawn multiple timers carefully when accessing
// simultaneously members of the SmartConsole class.
MyConsole.WriteInfo("\nWelcome to the Timers demo!\n")
// SetTimeout is called only once after the provided delay and
// is automatically removed by the TimerManager class
.SetTimeout(e =>
{
// this action is called back after 5.5 seconds; the name
// of the timer is useful should we want to clear it
// before this action gets executed
e.Console.Write("\n").WriteError("Time out occured after 5.5 seconds! " +
"Timer has been automatically disposed.\n");
// the next statement will make the current instance of
// SmartConsole throw an exception on the next prompt attempt
// e.Console.CancelRequested = true;
// use 5500 or any other value not multiple of 1000 to
// reduce write collision risk with the next timer
}, millisecondsDelay: 5500, name: "SampleTimeout")
.SetInterval(e =>
{
if (e.Ticks == 1)
{
e.Console.WriteLine();
}
e.Console.Write($"\rFirst timer tick: ", System.ConsoleColor.White)
.WriteInfo(e.TicksToSecondsElapsed());
if (e.Ticks > 4)
{
// we could remove the previous timeout:
// e.Console.ClearTimeout("SampleTimeout");
}
}, millisecondsInterval: 1000, "EverySecond")
// we can add as many timers as we want (or the computer's resources permit)
.SetInterval(e =>
{
if (e.Ticks == 1 || e.Ticks == 3) // 1.5 or 4.5 seconds to avoid write collision
{
e.Console.WriteSuccess("\nSecond timer is active...\n");
}
else if (e.Ticks == 5)
{
e.Console.WriteWarning("\nSecond timer is disposing...\n");
// doesn't dispose the timer
// e.Timer.Stop();
// clean up if we no longer need it
e.DisposeTimer();
}
else
{
System.Diagnostics.Trace.WriteLine($"Second timer tick: {e.Ticks}");
}
}, 1500)
.Prompt("\nPress Enter to stop the timers: ")
// makes sure that any remaining timer is disposed off
.ClearTimers()
.WriteSuccess("Timers cleared!\n");
}
}
}
''Alastair, you can use this lib and tool; DefiantJS. It enables XPath queries on JSON structures and you can test and validate this XPath:
//data[category="Politician"]
DefiantJS extends the global object with the method "search", which in turn returns an array with the matches. In Javascript, it'll look like this:
var person = JSON.search(json_data, "//people[category='Politician']");
console.log( person[0].name );
// Barack Obama
Nobody have mention the new type of "Pull to refresh" which shows on top of the action bar like in the Google Now or Gmail application.
There is a library ActionBar-PullToRefresh which works exactly the same.
You can also use the lastIndexOf() function to locate the last occurrence of the /
character in your URL, then the substring() function to return the substring starting from that location:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
I would do something like this
begin
for i in (select table_name from user_tables where table_name = 'FOO') loop
execute immediate 'drop table '||i.table_name;
end loop;
end;
execute immediate 'CREATE TABLE FOO (id NUMBER,
title VARCHAR2(4000)) ';
Multiple Image upload using php full source code and preview available at the below Link.
Sample code:
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path.md5(uniqid()).
".".$ext[count($ext) - 1]; //set the target path with a new name of image
$j = $j + 1; //increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
echo $j.
').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { //if file was not moved.
echo $j.
').<span id="error">please try again!.</span><br/><br/>';
}
} else { //if file size and file type was incorrect.
echo $j.
').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
http://www.allinworld99.blogspot.com/2015/05/php-multiple-file-upload.html
In certain scenarios utilizing Bash's concatenation ability might be appropriate.
temp='this string is very long '
temp+='so I will separate it onto multiple lines'
echo $temp
this string is very long so I will separate it onto multiple lines
name=[value]...
...In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value.
Bash.
The various UNIX and Linux implementations have various different source level implementations of ksh, some of which are real ksh, some of which are pdksh implementations and some of which are just symlinks to some other shell that has a "ksh" personality. This can lead to weird differences in execution behavior.
At least with bash you can be sure that it's a single code base, and all you need worry about is what (usually minimum) version of bash is installed. Having done a lot of scripting on pretty much every modern (and not-so-modern) UNIX, programming to bash is more reliably consistent in my experience.
For MySql WorkBench, Please use below :
update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12);
If you're using PHP and none of the above worked (as it was my case), you need to set the locale with utf-8 encoding.
Like this
setlocale(LC_ALL, 'fr_CA.utf-8');
You don't need to copy a Python string. They are immutable, and the copy
module always returns the original in such cases, as do str()
, the whole string slice, and concatenating with an empty string.
Moreover, your 'hello'
string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.
One way you could work around this is to actually create a new string, then slice that string back to the original content:
>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)
But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.
If all you wanted to know is how much memory a Python object requires, use sys.getsizeof()
; it gives you the memory footprint of any Python object.
For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:
>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360
You can then choose to use id()
tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.
You may also do:
YourAsyncFunctionName = async (value) => {
/* Code goes here */
}
I found it easier to edit the project file directly e.g. YourApp.csproj.
You can do this by modifying ApplicationIcon
property element:
<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>
Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.
flask.Flask.run
accepts additional keyword arguments (**options
) that it forwards to werkzeug.serving.run_simple
- two of those arguments are threaded
(a boolean) and processes
(which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).
threaded
defaults to True
as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True
to enable this behaviour.
For example, you can do
if __name__ == '__main__':
app.run(threaded=True)
to handle multiple clients using threads in a way compatible with old Flask versions, or
if __name__ == '__main__':
app.run(threaded=False, processes=3)
to tell Werkzeug to spawn three processes to handle incoming requests, or just
if __name__ == '__main__':
app.run()
to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.
That being said, Werkzeug's serving.run_simple
wraps the standard library's wsgiref
package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).
another solution is to open the file by winword and save it as txt and then reopen it by excel and it will work ISA
You can just add a parameter to run, see:
Run --> Parameters
In field parameters add -cleaninstall
Now just run, they always will do a deep clean before install.
The best way to center a box both vertically and horizontally, is to use two containers :
##The outher container :
display: table;
##The inner container :
display: table-cell;
vertical-align: middle;
text-align: center;
##The content box :
display: inline-block;
##Demo :
body {
margin : 0;
}
.outer-container {
display: table;
width: 80%;
height: 120px;
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
_x000D_
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
_x000D_
See also this Fiddle!
##Centering in the middle of the page:
To center your content in the middle of your page, add the following to your outer container :
position : absolute;
width: 100%;
height: 100%;
Here's a demo for that :
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
_x000D_
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
_x000D_
See also this Fiddle!
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
.md
stands for markdown and is generated at the bottom of your github page as html.
Typical syntax includes:
Will become a heading
==============
Will become a sub heading
--------------
*This will be Italic*
**This will be Bold**
- This will be a list item
- This will be a list item
Add a indent and this will end up as code
For more details: http://daringfireball.net/projects/markdown/
SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
-- <add any columns to outer select from inner query>
FROM
( -- your query here --
select 'CARAT Issue Open' issue_comment, ...., ...,
substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
from ....
where UPPER(ISSUE_STATUS) like '%OPEN%'
)
WHERE... -- optional --
To fix this, we had to changed the AppPool Identity to an administrator account.
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
print "financial return of outcome 1 = $%.2f" % (out1)
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
I'm maybe a little bit late but I'm currently trying to develop a program which can brute force a password protected zip archive. First I tried all commands I found in the internet to extract it through cmd... But it never worked....Every time I tried it, the cmd output said, that the key was wrong but it was right. I think they just disenabled this function in a current version.
What I've done to Solve the problem was to download an older 7zip version(4.?) and to use this for extracting through cmd.
This is the command: "C:/Program Files (86)/old7-zip/7z.exe" x -pKey "C:/YOURE_ZIP_PATH"
The first value("C:/Program Files (86)/old7-zip/7z.exe") has to be the path where you have installed the old 7zip to. The x is for extract and the -p For you're password. Make sure you put your password without any spaces behind the -p! The last value is your zip archive to extract. The destination where the zip is extracted to will be the current path of cmd. You can change it with: cd YOURE_PATH
Now I let execute this command through java with my password trys. Then I check the error output stream of cmd and if it is null-> then the password is right!
I'm a bit surprised nobody is using the backspace character. Here's one that uses it.
import sys
import time
secs = 1000
while True:
time.sleep(1) #wait for a full second to pass before assigning a second
secs += 1 #acknowledge a second has passed
sys.stdout.write(str(secs))
for i in range(len(str(secs))):
sys.stdout.write('\b')
Update for iOS 7
Apple docs for UIActionSheet: UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy
I recommend against trying to customize the contents of an ActionSheet, as it can lead to serious invalid context errors in iOS 7. I just spent a few hours working through this problem and ultimately decided to take a different approach. I replaced the call to show the action sheet with a modal view controller containing a simple tableview.
There are many ways to accomplish this. Here's one way that I just implemented in a current project. It's nice because I can reuse it between 5 or 6 different screens where I all users to select from a list of options.
SimpleTableViewController
.SimpleTableViewControllerDelegate
with a required method itemSelectedatRow:
, and a weak property called delegate of type id<SimpleTableViewControllerDelegate>
. This is how we will pass the selection back to the parent controller.itemSelectedatRow:
in tableView:didSelectRowAtIndexPath:
.This approach has the added benefit of being fairly reusable. To use, import the SimpleTableViewController class in your ViewController.h, conform to the SimpleTableViewDelegate, and implement the itemSelectedAtRow:
method. Then, to open the modal just instantiate a new SimpleTableViewController, set the table data and delegate, and present it.
UINavigationController *navigationController = (UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:@"SimpleTableVC"];
SimpleTableViewController *tableViewController = (SimpleTableViewController *)[[navigationController viewControllers] objectAtIndex:0];
tableViewController.tableData = self.statesArray;
tableViewController.navigationItem.title = @"States";
tableViewController.delegate = self;
[self presentViewController:navigationController animated:YES completion:nil];
I create a simple example and posted it on github.
Also see Showing actionsheet causes CGContext invalid context errors.
wait until this call is finish its executing
You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground
execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
To get result back in UI Thread start AsyncTask
as :
String str_result= new RunInBackGround().execute().get();
I had the same problem earlier when I tried to edit an open source project from the internet .
Solved it by just Cleaning the solution and rebuilding it .
Hope this helps.