From the Aspose Cells forums: How to use new line char with in a cell?
After you supply text you should set the cell's IsTextWrapped style to true
worksheet.Cells[0, 0].Style.WrapText = true;
I had the same problem
I downloaded latest pip from https://pypi.org/project/pip/#files
and then.... pip install << downloaded file location >>
then pygame and kivy installation worked... Thanks...!!
You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.
Google gives a breakdown of these fields in the Evaluating network performance section of their DevTools documentation.
Stalled/Blocking
Time the request spent waiting before it could be sent. This time is inclusive of any time spent in proxy negotiation. Additionally, this time will include when the browser is waiting for an already established connection to become available for re-use, obeying Chrome's maximum six TCP connection per origin rule.
(If you forget, Chrome has an "Explanation" link in the hover tooltip and under the "Timing" panel.)
Basically, the primary reason you will see this is because Chrome will only download 6 files per-server at a time and other requests will be stalled until a connection slot becomes available.
This isn't necessarily something that needs fixing, but one way to avoid the stalled state would be to distribute the files across multiple domain names and/or servers, keeping CORS in mind if applicable to your needs, however HTTP2 is probably a better option going forward. Resource bundling (like JS and CSS concatenation) can also help to reduce amount of stalled connections.
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
Simpler with the aggregate function string_agg()
(Postgres 9.0 or later):
SELECT movie, string_agg(actor, ', ') AS actor_list
FROM tbl
GROUP BY 1;
The 1
in GROUP BY 1
is a positional reference and a shortcut for GROUP BY movie
in this case.
string_agg()
expects data type text
as input. Other types need to be cast explicitly (actor::text
) - unless an implicit cast to text
is defined - which is the case for all other character types (varchar
, character
, "char"
), and some other types.
As isapir commented, you can add an ORDER BY
clause in the aggregate call to get a sorted list - should you need that. Like:
SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM tbl
GROUP BY 1;
But it's typically faster to sort rows in a subquery. See:
They are the same.
Both mean that when coming in to the load balancer, the request will be directed to the server that served the first request (and has the session).
Recently I learned of the following syntax:
DELETE (SELECT *
FROM productfilters pf
INNER JOIN product pr
ON pf.productid = pr.id
WHERE pf.id >= 200
AND pr.NAME = 'MARK')
I think it looks much cleaner then other proposed code.
I coded a C# version based on JAVA ANPR, but I changed the awt library functions with OpenCV. You can check it at http://anprmx.codeplex.com
For reference, this is a Kotlin implementation of @danh32's solution:
private fun getWebviewScale (contentWidth : Int) : Int {
val dm = DisplayMetrics()
windowManager.defaultDisplay.getRealMetrics(dm)
val pixWidth = dm.widthPixels;
return (pixWidth.toFloat()/contentWidth.toFloat() * 100F)
.toInt()
}
In my case, width was determined by three images to be 300 pix so:
webview.setInitialScale(getWebviewScale(300))
It took me hours to find this post. Thanks!
Example for escaped string with variable:
@some-variable-height: 10px;
...
div {
height: ~"calc(100vh - "@some-variable-height~")";
}
compiles to
div {
height: calc(100vh - 10px );
}
I've discovered that it's difficult to find an answer that you can use out-of-the box in your Swift 3 project. The main problem of other answers that they don't honor the alpha-channel of the image. Here is the technique that I'm using in my projects.
extension UIImage {
func scaledToFit(toSize newSize: CGSize) -> UIImage {
if (size.width < newSize.width && size.height < newSize.height) {
return copy() as! UIImage
}
let widthScale = newSize.width / size.width
let heightScale = newSize.height / size.height
let scaleFactor = widthScale < heightScale ? widthScale : heightScale
let scaledSize = CGSize(width: size.width * scaleFactor, height: size.height * scaleFactor)
return self.scaled(toSize: scaledSize, in: CGRect(x: 0.0, y: 0.0, width: scaledSize.width, height: scaledSize.height))
}
func scaled(toSize newSize: CGSize, in rect: CGRect) -> UIImage {
if UIScreen.main.scale == 2.0 {
UIGraphicsBeginImageContextWithOptions(newSize, !hasAlphaChannel, 2.0)
}
else {
UIGraphicsBeginImageContext(newSize)
}
draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? UIImage()
}
var hasAlphaChannel: Bool {
guard let alpha = cgImage?.alphaInfo else {
return false
}
return alpha == CGImageAlphaInfo.first ||
alpha == CGImageAlphaInfo.last ||
alpha == CGImageAlphaInfo.premultipliedFirst ||
alpha == CGImageAlphaInfo.premultipliedLast
}
}
Example of usage:
override func viewDidLoad() {
super.viewDidLoad()
let size = CGSize(width: 14.0, height: 14.0)
if let image = UIImage(named: "barbell")?.scaledToFit(toSize: size) {
let imageView = UIImageView(image: image)
imageView.center = CGPoint(x: 100, y: 100)
view.addSubview(imageView)
}
}
This code is a rewrite of Apple's extension with added support for images with and without alpha channel.
As a further reading I recommend checking this article for different image resizing techniques. Current approach offers decent performance, it operates high-level APIs and easy to understand. I recommend sticking to it unless you find that image resizing is a bottleneck in your performance.
I have remixed the answer by @isubuz and this answer by @Umur Kontaci on attribute directives into a version where your controller doesn't call a DOM-like operation like "dismiss", but instead tries to be more MVVM style, setting a boolean property isInEditMode
. The view in turn links this bit of info to the attribute directive that opens/closes the bootstrap modal.
var app = angular.module('myApp', []);_x000D_
_x000D_
app.directive('myModal', function() {_x000D_
return {_x000D_
restrict: 'A',_x000D_
scope: { myModalIsOpen: '=' },_x000D_
link: function(scope, element, attr) {_x000D_
scope.$watch(_x000D_
function() { return scope.myModalIsOpen; },_x000D_
function() { element.modal(scope.myModalIsOpen ? 'show' : 'hide'); }_x000D_
);_x000D_
}_x000D_
} _x000D_
});_x000D_
_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
$scope.isInEditMode = false;_x000D_
$scope.toggleEditMode = function() { _x000D_
$scope.isInEditMode = !$scope.isInEditMode;_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MyCtrl as vm">_x000D_
_x000D_
<div class="modal fade" my-modal my-modal-is-open="isInEditMode">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-body">_x000D_
Modal body! IsInEditMode == {{isInEditMode}}_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button class="btn" ng-click="toggleEditMode()">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p><button class="btn" ng-click="toggleEditMode()">Toggle Edit Mode</button></p> _x000D_
<pre>isInEditMode == {{isInEditMode}}</pre>_x000D_
_x000D_
</div>
_x000D_
In Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.
So instead of:
chkconfig enable apache2
You should look for the service name, and then enable it
systemctl status apache2
systemctl enable apache2.service
Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.
You need to configure a raw HttpClient with SSL support, something like this:
@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient httpClient
= HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory
= new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
ResponseEntity<String> response
= new RestTemplate(requestFactory).exchange(
urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
You are confusing 'sets' and 'lists'. A set does not guarantee order, but lists do.
Sets are declared using curly brackets: {}
. In contrast, lists are declared using square brackets: []
.
mySet = {a, b, c, c}
Does not guarantee order, but list does:
myList = [a, b, c]
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload
callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token
here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
Route::get('/your-route-to-editor', function () {
return view('your-view');
});
Route::post('/your-route-to-processor', function (Request $request) {
$this->validate($request, [
'editordata' => 'required',
]);
$data = $request->input('editordata');
//loading the html data from the summernote editor and select the img tags from it
$dom = new \DomDocument();
$dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
//for now src attribute contains image encrypted data in a nonsence string
$data = $img->getAttribute('src');
//getting the original file name that is in data-filename attribute of img
$file_name = $img->getAttribute('data-filename');
//extracting the original file name and extension
$arr = explode('.', $file_name);
$upload_base_directory = 'public/';
$original_file_name='time()'.$k;
$original_file_extension='png';
if (sizeof($arr) == 2) {
$original_file_name = $arr[0];
$original_file_extension = $arr[1];
}
else
{
//the file name contains extra . in itself
$original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
$original_file_extension = $arr[sizeof($arr)-1];
}
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;
//uploading the image to an actual file on the server and get the url to it to update the src attribute of images
Storage::put($path, $data);
$img->removeAttribute('src');
//you can remove the data-filename attribute here too if you want.
$img->setAttribute('src', Storage::url($path));
// data base stuff here :
//saving the attachments path in an array
}
//updating the summernote WYSIWYG markdown output.
$data = $dom->saveHTML();
// data base stuff here :
// save the post along with it attachments array
return view('your-preview-page')->with(['data'=>$data]);
});
And to add to this topic, here're my experiences below... Really odd and time consuming so I thought it was worth adding.
I've had a similar problem trying to built the portlet-bridge on Windows, getting the following errors:
Downloading: http://repo1.maven.org/maven2/org/apache/portals/bridges-pom/1.0/bridges-pom-1.0.pom [DEBUG] Reading resolution tracking file C:\Documents and Settings\myuser\.m2\repository\org\apache\portals\bridges-pom\1.0\bridges-pom-1.0.pom.lastUpdated [DEBUG] Writing resolution tracking file C:\Documents and Settings\myuser\.m2\repository\org\apache\portals\bridges-pom\1.0\bridges-pom-1.0.pom.lastUpdated [ERROR] The build could not read 1 project -> [Help 1] org.apache.maven.project.ProjectBuildingException: Some problems were encountered while processing the POMs: [FATAL] Non-resolvable parent POM: Could not transfer artifact org.apache.portals:bridges-pom:pom:1.0 from/to central (http://repo1.maven.org/maven2): Error transferring file: repo1.maven.org and 'parent.relativePath' points at wrong local POM @ line 23, column 11 ... [ERROR] The project org.apache.portals.bridges:portals-bridges-common:2.0 (H:\path_to_project\portals-bridges-common-2.0\pom.xml) has 1 error [ERROR] Non-resolvable parent POM: Could not transfer artifact org.apache.portals:bridges-pom:pom:1.0 from/to central (http://repo1.maven.org/maven2): Error transferring file: repo1.maven.org and 'parent.relativePath' points at wrong local POM @ line 23, column 11: Unknown host repo1.maven.org -> [Help 2] ... [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException [ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
I tried a couple of things, following a bit of surfing:
Tried to set the parent.relativePath as empty so that maven didn't think the parent was local. This is as per the suggestion on SO at Hudson build fail: Non-resolvable parent POM and in this nabble forum. This had no effect.
I also tried ensuring the repository was explicitly listed in my settings.xml but this had no effect either.
I then ensured mvn was forced to lookup the repository, rather than rely on it's own history, as discussed in this blog by Sarthon. Unfortunately, this wasn't the issue either.
In some desperation, I then revisited my MAVEN_OPTS to ensure I wasn't falling foul of my proxy settings. These were correct, albeit with the value unquoted:
set MAVEN_OPTS= -Dhttp.proxyHost=myproxy.mycompany.com -Dhttp.proxyPort=8080 -Xmx256m
So, finally, I moved the proxy config into my settings.xml and this worked:
<proxies>
<proxy>
<id>genproxy</id>
<active>true</active>
<protocol>http</protocol>
<!--username>proxyuser</username-->
<!--password>proxypass</password-->
<host>myproxy.mycompany.com</host>
<port>8080</port>
<nonProxyHosts>*.mycompany.com|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
Really not sure why my original MAVEN_OPTS wasn't working (quotes?) while the settings.xml config did work. I'd like to reverse the fix and check each step again but have wasted too much time. Will report back as and when.
The easiest way to pass ArrayList using intent
Add this line in dependencies block build.gradle.
implementation 'com.google.code.gson:gson:2.2.4'
pass arraylist
ArrayList<String> listPrivate = new ArrayList<>();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("private_list", new Gson().toJson(listPrivate));
startActivity(intent);
retrieve list in another activity
ArrayList<String> listPrivate = new ArrayList<>();
Type type = new TypeToken<List<String>>() {
}.getType();
listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
You can use object also instead of String in type
Works for me..
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
I had the same issue (even though the project was compiling/working fine in Eclipse), it was not when using the command line build. The reason was that I wasn't using the correct folder structure for mvn: "src/main/java/com" etc. It is looking at these folders by default (I was using "/scr/main/com" etc. which caused issues).
Performance test:
http://jsperf.com/array-clear-methods/3
a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length) // 97% slower
while (a.length > 0) {
a.pop();
} // Fastest
There is now a mysql-client
formula.
brew install mysql-client
You can use @Bean
to make an existing third-party class available to your Spring framework application context.
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
By using the @Bean
annotation, you can wrap a third-party class (it may not have @Component
and it may not use Spring), as a Spring bean. And then once it is wrapped using @Bean
, it is as a singleton object and available in your Spring framework application context. You can now easily share/reuse this bean in your app using dependency injection and @Autowired
.
So think of the @Bean
annotation is a wrapper/adapter for third-party classes. You want to make the third-party classes available to your Spring framework application context.
By using @Bean
in the code above, I'm explicitly declare a single bean because inside of the method, I'm explicitly creating the object using the new
keyword. I'm also manually calling setter methods of the given class. So I can change the value of the prefix field. So this manual work is referred to as explicit creation. If I use the @Component
for the same class, the bean registered in the Spring container will have default value for the prefix field.
On the other hand, when we annotate a class with @Component
, no need for us to manually use the new
keyword. It is handled automatically by Spring.
1.Install angular-animate
2.Add the animation effect to the class ng-enter
for page entering animation and the class ng-leave
for page exiting animation
for reference: this page has a free resource on angular view transition https://e21code.herokuapp.com/angularjs-page-transition/
Many people like to have private fields prefixed with an underscore. It is just a naming convention.
C#'s 'official' naming conventions prescribe simple lowercase names (no underscore) for private fields.
I'm not aware of standard conventions for C++, although underscores are very widely used.
S3 does not have directories, while you can list files in a pseudo directory manner like you demonstrated, there is no directory "file" per-se.
You may of inadvertently created a data file called users/<user-id>/contacts/<contact-id>/
.
If you want the external public IP and you're in a cloud environment like AWS or Azure, you can use the ipify_facts module:
# TODO: SECURITY: This requires that we trust ipify to provide the correct public IP. We could run our own ipify server.
- name: Get my public IP from ipify.org
ipify_facts:
This will place the public IP into the variable ipify_public_ip
.
You have duplicated export default
declaration. The first one get overridden by second one which is actually a function.
Path Variables dialog has nothing to do with the environment variables.
Environment variables can be specified in your OS or customized in the Run configuration:
I usually do it using add_all
.
from app import session
from models import User
objects = [User(name="u1"), User(name="u2"), User(name="u3")]
session.add_all(objects)
session.commit()
If you are storing metadata in a tag use data attributes eg.
<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>
Now use the attribute to get the name of the song
var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();
You could do an SQLDump
of the database (and its data) then search that file.
In WAMP the files are served by the Apache component (the A in WAMP).
In Apache, by default the files served are located in the subdirectory htdocs
of the installation directory. But this can be changed, and is actually changed when WAMP installs Apache.
The location from where the files are served is named the DocumentRoot
, and is defined using a variable in Apache configuration file. The default value is the subdirectory htdocs
relative to what is named the ServerRoot
directory.
By default the ServerRoot
is the installation directory of Apache. However this can also be redefined into the configuration file, or using the -d
option of the command httpd
which is used to launch Apache. The value in the configuration file overrides the -d
option.
The configuration file is by default conf/httpd.conf
relative to ServerRoot
. But this can be changed using the -f
option of command httpd.
When WAMP installs itself, it modify the default configuration file with DocumentRoot c:/wamp/www/
. The files to be served need to be located here and not in the htdocs
default directory.
You may change this location set by WAMP, either by modifying DocumentRoot
in the default configuration file, or by using one of the two command line options -f
or -d
which point explicitly or implicity to a new configuration file which may hold a different value for DocumentRoot
(in that case the new file needs to contain this definition, but also the rest of the configuration found in the default configuration file).
Experimentally, I've discovered that you can provide:
<b>…</b>
for boldface,<i>…</i>
for italics,<u>…</u>
for underline,<br />
to enforce a single line break,http://google.com
; this appears as a hyperlink.<a>
tag for a custom description does not work and breaks the formatting.)→
(→), ™
(™) and ®
(®); consult this W3 reference for the exhaustive list.• 
yields "• ").Special notes concerning only Google Play app:
<blockquote>…</blockquote>
to indent a paragraph of text,<small>…</small>
for slightly smaller text,<big>…</big>
for slightly larger text,<sup>…</sup>
and <sub>…</sub>
for super- and subscripts.<font color="#a32345">…</font>
for setting font colors in HEX code.Special notes concerning only Google Play website:
The only thing that would apply this without additional methods is elif
as the following example
a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b:
print('monthly')
elif 'quartly' in b:
print('quartly')
elif 'semiannual' in b:
print('semiannual')
elif 'yearly' in b:
print('yearly')
else:
print('final')
The text 'dasda' will never not be within a tag, right? Semantically and to be valid HTML it as to be, just add the clear class to that:
Node has builtin support for gzip and deflate via the zlib module:
var zlib = require('zlib');
zlib.gunzip(gzipBuffer, function(err, result) {
if(err) return console.error(err);
console.log(result);
});
Edit: You can even pipe
the data directly through e.g. Gunzip
(using request):
var request = require('request'),
zlib = require('zlib'),
fs = require('fs'),
out = fs.createWriteStream('out');
// Fetch http://example.com/foo.gz, gunzip it and store the results in 'out'
request('http://example.com/foo.gz').pipe(zlib.createGunzip()).pipe(out);
For tar archives, there is Isaacs' tar module, which is used by npm.
Edit 2: Updated answer as zlib
doesn't support the zip
format. This will only work for gzip
.
Here you have an example working on py2.6 and py3.2:
from scipy.stats import norm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# read data from a text file. One number per line
arch = "test/Log(2)_ACRatio.txt"
datos = []
for item in open(arch,'r'):
item = item.strip()
if item != '':
try:
datos.append(float(item))
except ValueError:
pass
# best fit of data
(mu, sigma) = norm.fit(datos)
# the histogram of the data
n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=2)
#plot
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma))
plt.grid(True)
plt.show()
You can just do this:
git remote add origin ssh://user@host:1234/srv/git/example
1234
is the ssh port being used
There is a workaround by capturing clicks on document.body
and then checking event target.
document.body.addEventListener( 'click', function ( event ) {
if( event.srcElement.id == 'btnSubmit' ) {
someFunc();
};
} );
EDIT: make sure you set this drawable as LOGO, not as your app icon like some of the commenters did.
Just make an XML drawable and put it in the resource folder "drawable" (without any density or other configuration).
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:drawable="@drawable/my_logo"
android:right="10dp"/>
</layer-list>
The last step is to set this new drawable as logo in your manifest (or on the Actionbar object in your activity)
Good luck!
Well I encountered a similar problem. The problem for me is that the JS file get loaded before the DOM render happens. So move your <script>
to the end of <body>
tag.
or use defer.
<script defer src="">
so rest assured e.preventDefault()
should work.
Use this library, It is simple and easy.. https://github.com/hotchemi/Android-Rate
by adding the dependency..
dependencies {
compile 'com.github.hotchemi:android-rate:0.5.6'
}
Adding /r/n between the Strings solved the problem for me. give it a try. On pasting dont include the '//' for excluding.
Eg: Option01\r\nOption02\r\nOption03
this will give output as
Option01
Option02
Option03
Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
Try the following script:
Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO
Also
I prefer(After a long search) to use the following script, it contains @fillfactor
determines how much percentage of the space on each leaf-level page is filled with data.
DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
for more info, check the following link:
and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:
SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc
For more information, Check the following link:
Monolithic stylesheets do offer a lot of benefits (which are described in the other answers), however depending on the overall size of the stylesheet document you could run into problems in IE. IE has a limitation with how many selectors it will read from a single file. The limit is 4096 selectors. If you're monolithic stylesheet will have more than this you will want to split it. This limitation only rears it's ugly head in IE.
This is for all versions of IE.
See Ross Bruniges Blog and MSDN AddRule page.
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
In a nutshell, if you turn on the OAuth 2.0
for Canvas advanced option, Facebook will send a $_REQUEST['signed_request']
along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
The cURL extension to PHP is designed to allow you to use a variety of web resources from within your PHP script.
Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.
This, however works:
<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>
PROBLEM RESOLVED
In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:
But the correct way is to pass the value of url as:
url: "site/cgi-bin/serverApp.php"
Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:
http://mydomain.com/site/index.html
And put
http://www.mydomain.com/site/index.html
In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file
base href="http://mydomain.com/" <--- bad idea, remove it!
If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!
I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:
header('Content-type: application/json');
to ensure that browser get the data as "json data" ...
I was playing around with the following code for another question on StackOverflow and thought that it might be appropriate for here. The function printList2 allows the use of a regex and lists all the occurrences in order. (printList was an attempt at an earlier solution, but it failed in a number of cases.)
<html>_x000D_
<head>_x000D_
<title>Checking regex</title>_x000D_
<script>_x000D_
var string1 = "123xxx5yyy1234ABCxxxabc";_x000D_
var search1 = /\d+/;_x000D_
var search2 = /\d/;_x000D_
var search3 = /abc/;_x000D_
function printList(search) {_x000D_
document.writeln("<p>Searching using regex: " + search + " (printList)</p>");_x000D_
var list = string1.match(search);_x000D_
if (list == null) {_x000D_
document.writeln("<p>No matches</p>");_x000D_
return;_x000D_
}_x000D_
// document.writeln("<p>" + list.toString() + "</p>");_x000D_
// document.writeln("<p>" + typeof(list1) + "</p>");_x000D_
// document.writeln("<p>" + Array.isArray(list1) + "</p>");_x000D_
// document.writeln("<p>" + list1 + "</p>");_x000D_
var count = list.length;_x000D_
document.writeln("<ul>");_x000D_
for (i = 0; i < count; i++) {_x000D_
document.writeln("<li>" + " " + list[i] + " length=" + list[i].length + _x000D_
" first position=" + string1.indexOf(list[i]) + "</li>");_x000D_
}_x000D_
document.writeln("</ul>");_x000D_
}_x000D_
function printList2(search) {_x000D_
document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");_x000D_
var index = 0;_x000D_
var partial = string1;_x000D_
document.writeln("<ol>");_x000D_
for (j = 0; j < 100; j++) {_x000D_
var found = partial.match(search);_x000D_
if (found == null) {_x000D_
// document.writeln("<p>not found</p>");_x000D_
break;_x000D_
}_x000D_
var size = found[0].length;_x000D_
var loc = partial.search(search);_x000D_
var actloc = loc + index;_x000D_
document.writeln("<li>" + found[0] + " length=" + size + " first position=" + actloc);_x000D_
// document.writeln(" " + partial + " " + loc);_x000D_
partial = partial.substring(loc + size);_x000D_
index = index + loc + size;_x000D_
document.writeln("</li>");_x000D_
}_x000D_
document.writeln("</ol>");_x000D_
_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p>Original string is <script>document.writeln(string1);</script></p>_x000D_
<script>_x000D_
printList(/\d+/g);_x000D_
printList2(/\d+/);_x000D_
printList(/\d/g);_x000D_
printList2(/\d/);_x000D_
printList(/abc/g);_x000D_
printList2(/abc/);_x000D_
printList(/ABC/gi);_x000D_
printList2(/ABC/i);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I found a solution for this problem try to run this command in terminal
ps -ef | grep postgres
kill process by this command
sudo kill -9 PID
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).
Use this also
NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];
Note - Your NSMakeRange(start, end)
should be NSMakeRange(start, end- start)
;
Complete example based on the excellent @Hackaholic's answer:
def get_process_id(name):
"""Return process ids found by (partial) name or regex.
>>> get_process_id('kthreadd')
[2]
>>> get_process_id('watchdog')
[10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61] # ymmv
>>> get_process_id('non-existent process')
[]
"""
child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
return [int(pid) for pid in response.split()]
ReentrantReadWriteLock
is a specialized lock whereas synchronized(this)
is a general purpose lock. They are similar but not quite the same.
You are right in that you could use synchronized(this)
instead of ReentrantReadWriteLock
but the opposite is not always true.
If you'd like to better understand what makes ReentrantReadWriteLock
special look up some information about producer-consumer thread synchronization.
In general you can remember that whole-method synchronization and general purpose synchronization (using the synchronized
keyword) can be used in most applications without thinking too much about the semantics of the synchronization but if you need to squeeze performance out of your code you may need to explore other more fine-grained, or special-purpose synchronization mechanisms.
By the way, using synchronized(this)
- and in general locking using a public class instance - can be problematic because it opens up your code to potential dead-locks because somebody else not knowingly might try to lock against your object somewhere else in the program.
Compact all collections in current database
db.getCollectionNames().forEach(function (collectionName) {
print('Compacting: ' + collectionName);
db.runCommand({ compact: collectionName });
});
All you need to do is change the string within the java.text.SimpleDateFormat
constructor to:
"MM-dd-yyyy HH:mm:ss".
Just use the appropriate letters to build the above string to match your input date.
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
String second = first.replaceFirst("(.)(.)", "$2$1");
With ES6, we now have a simple way to create an Array from a NodeList: the Array.from()
function.
// nl is a NodeList
let myArray = Array.from(nl)
For a simple way, use system()
:
#include <stdlib.h>
...
int status = system("./foo 1 2 3");
system()
will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256
).
The manpage for wait()
(in section 2, man 2 wait
on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED
and WEXITSTATUS
.
Alternatively, if you need to read foo's standard output, use popen(3)
, which returns a file pointer (FILE *
); interacting with the command's standard input/output is then the same as reading from or writing to a file.
When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.
This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.
always @(posedge clk) begin
if (reset == 1) begin // For an active high reset
data_reg = 8'b10101011;
end else begin
data_reg = next_data_reg;
end
end
I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.
A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:
Representation of the central controller (assuming there is one).
Representations of elevators
Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.
Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).
Representation of a human and cargo (may be important for factoring in maximal loads)
Representation of the building (in some cases, as certain floors may be blocked at times, etc.)
A library and demo with the complete source code for scrolling toolbars or any type of header can be downloaded here:
https://github.com/JohannBlake/JBHeaderScroll
Headers can be Toolbars, LinearLayouts, RelativeLayouts, or whatever type of view you use to create a header.
The scrollable area can be any type of scroll content including ListView, ScrollView, WebView, RecyclerView, RelativeLayout, LinearLayout or whatever you want.
There's even support for nested headers.
It is indeed a complex undertaking to synchronize headers (toolbars) and scrollable content the way it's done in Google Newsstand.
This library doesn't require implementing any kind of onScrollListener.
The solutions listed above by others are only half baked solutions that don't take into consideration that the top edge of the scrollable content area beneath the toolbar has to initially be aligned to the bottom edge of the toolbar and then during scrolling the content area needs to be repositioned and possibly resized. The JBHeaderScroll handles all these issues.
Yes, there is: you can capture the echo
ed text using ob_start
:
<?php function TestBlockHTML($replStr) {
ob_start(); ?>
<html>
<body><h1><?php echo($replStr) ?></h1>
</html>
<?php
return ob_get_clean();
} ?>
You can get it with:
var html = new System.Net.WebClient().DownloadString(siteUrl)
How about this?
SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal
What Django actually says is:
Userprofile table has data in it and there might be
new_field
values which are null, but I do not know, so are you sure you want to mark property as non nullable, because if you do you might get an error if there are values with NULL
If you are sure that none of values in the userprofile
table are NULL - fell free and ignore the warning.
The best practice in such cases would be to create a RunPython migration to handle empty values as it states in option 2
2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)
In RunPython migration you have to find all UserProfile
instances with empty new_field
value and put a correct value there (or a default value as Django asks you to set in the model).
You will get something like this:
# please keep in mind that new_value can be an empty string. You decide whether it is a correct value.
for profile in UserProfile.objects.filter(new_value__isnull=True).iterator():
profile.new_value = calculate_value(profile)
profile.save() # better to use batch save
Have fun!
Make sure that you're working with the version of Python that think you are. Within Python run import sys
and print(sys.version)
.
Select the correct package manager to install pymysql with:
sudo pip install pymysql
.sudo pip3 install pymysql
.sudo conda install pymysql
.sudo apt-get install pymysql
.If all else fails, install the package directly:
sudo python3 setup.py install
.This answer is a compilation of suggestions. Apart from the other ones proposed here, thanks to the comment by @cmaher on this related thread.
Easy. Use .shape
.
>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.
iisexpress
program is responsible for that.
http://www.iis.net/learn/extensions/using-iis-express/running-iis-express-from-the-command-line
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.
I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.
The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and where
condition inside joined sub-select.
In my example I want to fetch the newest DNS scan results (table scan_dns
) per group identified by watch_id
. I build the sub-query separately.
The SQL I want Eloquent to generate:
SELECT * FROM `scan_dns` AS `s`
INNER JOIN (
SELECT x.watch_id, MAX(x.last_scan_at) as last_scan
FROM `scan_dns` AS `x`
WHERE `x`.`watch_id` IN (1,2,3,4,5,42)
GROUP BY `x`.`watch_id`) AS ss
ON `s`.`watch_id` = `ss`.`watch_id` AND `s`.`last_scan_at` = `ss`.`last_scan`
I did it in the following way:
// table name of the model
$dnsTable = (new DnsResult())->getTable();
// groups to select in sub-query
$ids = collect([1,2,3,4,5,42]);
// sub-select to be joined on
$subq = DnsResult::query()
->select('x.watch_id')
->selectRaw('MAX(x.last_scan_at) as last_scan')
->from($dnsTable . ' AS x')
->whereIn('x.watch_id', $ids)
->groupBy('x.watch_id');
$qqSql = $subq->toSql(); // compiles to SQL
// the main query
$q = DnsResult::query()
->from($dnsTable . ' AS s')
->join(
DB::raw('(' . $qqSql. ') AS ss'),
function(JoinClause $join) use ($subq) {
$join->on('s.watch_id', '=', 'ss.watch_id')
->on('s.last_scan_at', '=', 'ss.last_scan')
->addBinding($subq->getBindings());
// bindings for sub-query WHERE added
});
$results = $q->get();
UPDATE:
Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
Because you send custom headers so your CORS request is not a simple request, so the browser first sends a preflight OPTIONS request to check that the server allows your request.
If you turn on CORS on the server then your code will work. You can also use JavaScript fetch instead (here)
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=My-First-Header,My-Second-Header';_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
type: 'POST',_x000D_
url: url,_x000D_
headers: {_x000D_
"My-First-Header":"first value",_x000D_
"My-Second-Header":"second value"_x000D_
}_x000D_
}).done(function(data) {_x000D_
alert(data[0].request.httpMethod + ' was send - open chrome console> network to see it');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Here is an example configuration which turns on CORS on nginx (nginx.conf file):
location ~ ^/index\.php(/|$) {_x000D_
..._x000D_
add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
if ($request_method = OPTIONS) {_x000D_
add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
add_header 'Content-Length' 0;_x000D_
add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
return 204;_x000D_
}_x000D_
}
_x000D_
Here is an example configuration which turns on CORS on Apache (.htaccess file)
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
# Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
#Header set Access-Control-Allow-Origin "http://example.com:3000"_x000D_
#Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Header set Access-Control-Allow-Origin "*"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
You need to destroy:
myLineChart.destroy();
Then re-initialize the chart:
var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);
String methods return the modified string.
k = [x.replace(' ', '') for x in hello]
Here is an updated version using lodash 4 and ES6
const result = _.chain(data)
.groupBy("color")
.toPairs()
.map(pair => _.zipObject(['color', 'users'], pair))
.value();
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
After data-binding, do this:
ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code
Or follow Brian's second suggestion if you want to do it in markup.
You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".
<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" />
df.to_html()
has a columns parameter.
Just pass the columns into the to_html()
method.
df.to_html(columns=['A','B','C','D','E','F','G'])
Java 8
If you are using Java 8 in your project and comparing java.sql.Timestamp
, you could use the LocalDate
class:
sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());
If you are using java.util.Date
, have a look at Istvan answer which is less ambiguous.
All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.
A simple way is you can do as follows
public static String stripQueryStringAndHashFromPath(String uri) {
return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}
Answer updated to Python 3.7 and more
Here is how you can turn a date-and-time object
(aka datetime.datetime
object, the one that is stored inside models.DateTimeField
django model field)
into a date object (aka datetime.date
object):
from datetime import datetime
#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)
# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)
# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()
And just to be clear, if you print those elements, here is the output :
print(datetime_element)
2020-07-10 12:56:54.324893
print(date_element)
2020-07-10
Use 0.0.0.0
for addresses to be able to connect form any remote machine i.e.:
-Xdebug -Xrunjdwp:transport=dt_socket,address=0.0.0.0:8000,server=y,suspend=y
This thread is a little old but this worked for me:
numberString = "onetwothreefourfivesixseveneightninefiveten"
testString = "five"
marker = 0
while marker < len(numberString):
try:
print(numberString.index("five",marker))
marker = numberString.index("five", marker) + 1
except ValueError:
print("String not found")
marker = len(numberString)
setInterval returns an id that you can use to cancel the interval with clearInterval()
Options -Indexes
I have to try create .htaccess file that current directory that i want to disallow directory index listing. But, sorry i don't know about recursive in .htaccess code.
Try it.
If the first cell returned is a null
, the result in .NET will be DBNull.Value
If no cells are returned, the result in .NET will be null
; you cannot call ToString()
on a null
. You can of course capture what ExecuteScalar
returns and process the null
/ DBNull
/ other cases separately.
Since you are grouping etc, you presumably could potentially have more than one group. Frankly I'm not sure ExecuteScalar
is your best option here...
Additional: the sql in the question is bad in many ways:
I strongly suggest you parameterize; perhaps with something like "dapper" to make it easy:
int count = conn.Query<int>(
@"select COUNT(idemp_atd) absentDayNo from td_atd
where absentdate_atd between @sdate and @edate
and idemp_atd=@idemp group by idemp_atd",
new {sdate, edate, idemp}).FirstOrDefault();
all problems solved, including the "no rows" scenario. The dates are passed as dates (not strings); the injection hole is closed by use of a parameter. You get query-plan re-use as an added bonus, too. The group by
here is redundant, BTW - if there is only one group (via the equality condition) you might as well just select COUNT(1)
.
There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.
For Instance;
public getCustomCss() {
//Logic here;
if(this.x == this.y){
return 'class1'
}
if(this.x == this.z){
return 'class2'
}
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>
//OR
get customCss() {
//Logic here;
if(this.x == this.y){
return 'class1'
}
if(this.x == this.z){
return 'class2'
}
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>
On Mac OSX, manually delete these 2 directories under your pathToPython/site-packages/ will work:
for example, to remove pyasn1, which is a distutils installed project:
To find out where is your site-packages:
python -m site
Using D3:
If you want to re-inserts each selected element, in order, as the last child of its parent.
selection.raise()
I have an answer for you Yes, It is possible.
Go to
SQL Server Management Studio > select Database > click on attach
Then select and add .mdf and .ldf file. Click on OK.
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
Here is my solution:
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)
A particular example:
I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME
so that maven picks up what I want for each build. I did the following:
j6.sh
script which simply does export JAVA_HOME=...
path to j6 install...j6.sh
in that respective command terminal. By default, my JAVA_HOME
is set to J7.Hope this helps.
I had the same problem. Spring boot knows where static html files are located.
Didn't see any answers correctly using DATE_ADD
or DATE_SUB
:
Subtract 1 day from NOW()
...WHERE DATE_FIELD >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Add 1 day from NOW()
...WHERE DATE_FIELD >= DATE_ADD(NOW(), INTERVAL 1 DAY)
I was having same problem. I was getting error when i tried to run in my android device not emulator.
sudo ionic run android
I am able to fix this by running
adb uninstall com.mypackage.name
Follow this, it can be like what you are looking:
var obj = {_x000D_
Objone: 'one',_x000D_
Objtwo: 'two'_x000D_
};_x000D_
_x000D_
var key = "Objone";_x000D_
delete obj[key];_x000D_
console.log(obj); // prints { "objtwo": two}
_x000D_
Just copy and paste the code in HTML file. and enjoy the happy coding. Using Youtube api to manage the thumbnail of youtube embedded video.
<!DOCTYPE html>
<html>
<body>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event) {
$('#play_vid').click(function() {
event.target.playVideo();
});
}
$(document).ready(function() {
$('#player').hide();
$('#play_vid').click(function() {
$('#player').show();
$('#play_vid').hide();
});
});
</script>
<div id="player"></div>
<img id="play_vid" src="YOUR_IMAGE_PATH" />
</body>
</html>
The function move.CompleteMove(events)
that you use within your class probably doesn't contain a return
statement. So nothing is returned to self.values
(==> None). Use return
in move.CompleteMove(events)
to return whatever you want to store in self.values
and it should work. Hope this helps.
Just to add to the noise here, you could create an extension method:
public static bool IsWithin(this int value, int minimum, int maximum)
{
return value >= minimum && value <= maximum;
}
Which would let you do something like...
int val = 15;
bool foo = val.IsWithin(5,20);
That being said, this seems like a silly thing to do when the check itself is only one line.
One thing you could try is using the following css:
.child-element {
padding-left: inherit;
padding-right: inherit;
position: absolute;
left: 0;
right: 0;
}
It lets the child element inherit the padding from the parent, then the child can be positioned to match the parents widht and padding.
Also, I am using box-sizing: border-box;
for the elements involved.
I have not tested this in all browsers, but it seems to be working in Chrome, Firefox and IE10.
1.
if(!($user_id || $user_name || $user_logged)){
//do your stuff
}
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar["user_id"], etc.
In jQuery, you can use
$(".className").attr("style","");
The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.
class X {
const int x;
};
Since X::x
is const
, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x
). You can get the same kind of situation with a member that's a reference:
class X {
whatever &x;
};
It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.
This is why a const
member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.
It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
<View style={{flexDirection:'row'}}> <Text style={{ flex: number }}> You miss fdddddd dddddddd You miss fdd </Text> </View>
{ flex: aNumber } is all you need!
Just set 'flex' to a number that suit for you. And then the text will wrap.
I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...
There is a line of code to uncommment in order to have it return JSON.
{!! Form::text('firstname', null !!}
@if($errors->has('firstname'))
{{ $errors->first('firstname') }}
@endif
another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:
UserZone = User.zones.through
# for a single zone
users_in_zone = User.objects.filter(
id__in=UserZone.objects.filter(zone=zone1).values('user'))
# for multiple zones
users_in_zones = User.objects.filter(
id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))
it would be nice if it didn't need the .values('user')
specified, but Django (version 3.0.7) seems to need it.
the above code will end up generating SQL that looks something like:
SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))
which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned
Client
Do not set the content-type header.
// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');
fetch("api/SampleData",
{
body: formData,
method: "post"
});
Server
Use the FromForm
attribute to specify that binding source is form data.
[Route("api/[controller]")]
public class SampleDataController : Controller
{
[HttpPost]
public IActionResult Create([FromForm]UserDto dto)
{
return Ok();
}
}
public class UserDto
{
public string Name { get; set; }
public string Password { get; set; }
}
Who likes directly to the point,
In your Config
<appSettings>
<add key="Conf_id" value="71" />
</appSettings>
in your code(c#)
///SET
ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
///GET
string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();
This code will help you, and it's fairly self-explanatory:
#include <stdio.h> /* Standard Library of Input and Output */
#include <complex.h> /* Standard Library of Complex Numbers */
int main() {
double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;
printf("Working with complex numbers:\n\v");
printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));
double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));
double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));
double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));
double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));
double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));
return 0;
}
with:
creal(z1)
: get the real part (for float crealf(z1)
, for long double creall(z1)
)
cimag(z1)
: get the imaginary part (for float cimagf(z1)
, for long double cimagl(z1)
)
Another important point to remember when working with complex numbers is that functions like cos()
, exp()
and sqrt()
must be replaced with their complex forms, e.g. ccos()
, cexp()
, csqrt()
.
Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.
For example, you can validate the content negotiation like this.
This Accept
header prefers plain text so returns in that format:-
$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain
Whereas this one prefers JSON and so returns in that format:-
$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
"Accept": "application/json,text/*;q=0.99"
}
The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.
In your case .smallbox-paysummary
is defined after .smallbox
hence the 10px precedence.
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?
In version 2, instead of
from module import attribute1
you can do
attribute1 = module.attribute1
I'm using autolayout and none of the answers worked for me. Here is my solution that finally worked:
@property (nonatomic, assign) BOOL shouldScrollToLastRow;
- (void)viewDidLoad {
[super viewDidLoad];
_shouldScrollToLastRow = YES;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// Scroll table view to the last row
if (_shouldScrollToLastRow)
{
_shouldScrollToLastRow = NO;
[self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
}
}
If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()
MkdirAll
creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.
The path_test.go is a good illustration on how to use it:
func TestMkdirAll(t *testing.T) {
tmpDir := TempDir()
path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
err := MkdirAll(path, 0777)
if err != nil {
t.Fatalf("MkdirAll %q: %s", path, err)
}
defer RemoveAll(tmpDir + "/_TestMkdirAll_")
...
}
(Make sure to specify a sensible permission value, as mentioned in this answer)
You can use deleteDir()
as the last step of the pipeline Jenkinsfile (assuming you didn't change the working directory).
In your R script, called test.R
:
args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")
From the command line run:
R CMD BATCH -4 test.R
Your output file, test.Rout, will show that the argument 4
has been successfully passed to R:
cat test.Rout
> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user system elapsed
0.222 0.022 0.236
This is for windows environment:
I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword
I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.
I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:
#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');
fetch(request).then(function(response) {
// Convert to JSON
return response.json();
}).then(function(j) {
// Yay, `j` is a JavaScript object
console.log(JSON.stringify(j));
}).catch(function(error) {
console.log('Request failed', error)
});
using System;
using System.Collections.Generic;
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
Task.Run(() => MainAsync());
Console.ReadLine();
}
static async Task MainAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6740");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "login")
});
var result = await client.PostAsync("/api/Membership/exists", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}
}
With a thread:
private class LoadingThread extends Thread {
Handler handler;
LoadingThread(Handler h) {
handler = h;
}
@Override
public void run() {
Message m = handler.obtainMessage();
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String page = "";
String inLine;
while ((inLine = in.readLine()) != null) {
page += inLine;
}
in.close();
Bundle b = new Bundle();
b.putString("result", page);
m.setData(b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(m);
}
}
In my case, I came to this exception in two similar cases:
@Transactional
I had a call to another service (with long times of response). The method updates some properties of the entity (after the method, the entity still exists in the database). If the user requests two times the method (as he thinks it doesn't work the first time) when exiting from the transactional method the second time, Hibernate tries to update an entity which already changed its state from the beginning of the transaction. As Hibernate search for an entity in a state, and found the same entity but already changed by the first request, it throws an exception as it can't update the entity. It's like a conflict in GIT.Conclusion: in my case, it wasn't a problem which can be found in the code. This exception is thrown when Hibernate founds that the entity first fetched from the database changed during the current transaction, so it can't flush it to the database as Hibernate doesn't know which is the correct version of the entity: the one the current transaction fetch at the beginning; or the one already stored in the database.
Solution: to solve the problem, you will have to play with the Hibernate LockMode to find the one which best fit your requirements.
Your regular expression should be \btrue\b
to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:
string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string regexPattern = @"\btrue\b";
int numberOfTrues = Regex.Matches(searchText, regexPattern).Count;
Make sure the System.Text.RegularExpressions namespace is included at the top of the file.
Use <a>
with href instead of a <button>
solves my problem.
<ion-nav-buttons side="secondary">
<a class="button icon-right ion-plus-round" href="#/app/gosomewhere"></a>
</ion-nav-buttons>
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ"));
That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.
I think this is because you are using client software and not the server.
mysql
is client mysqld
is the serverTry:
sudo service mysqld start
To check that service is running use: ps -ef | grep mysql | grep -v grep
.
Uninstalling:
sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean
Re-Installing:
sudo apt-get update
sudo apt-get install mysql-server
Backup entire folder before doing this:
sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade
Also worth checking is if there are any errors in the return type of your interface methods. I could reproduce this issue by having an unintended return type like Call<Call<ResponseBody>>
DateTime is capable of storing only two distinct times, the local time and UTC. The Kind property indicates which.
DateTimeOffset expands on this by being able to store local times from anywhere in the world. It also stores the offset between that local time and UTC. Note how DateTime cannot do this unless you'd add an extra member to your class to store that UTC offset. Or only ever work with UTC. Which in itself is a fine idea btw.
SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';
This will select all the data between the 2 dates
Sorry to (re-)post here, people often don't expand comments.
Check my comment to crashmstr, FlexeLint / PC-Lint will do this for you. Informational message 766. Section 11.8.1 of my manual (version 8.0) discusses this.
Also, and this is important, keep iterating until the message goes away. In other words, after removing unused headers, re-run lint, more header files might have become "unneeded" once you remove some unneeded headers. (That might sound silly, read it slowly & parse it, it makes sense.)
Using Bootstrap 3's grid system:
<div class="container">
<div class="row">
<div class="col-xs-4">Menu</div>
<div class="col-xs-8">
<div class="row">
<div class="col-md-4 col-md-push-8">Right Content</div>
<div class="col-md-8 col-md-pull-4">Content</div>
</div>
</div>
</div>
</div>
Working example: http://bootply.com/93614
First, we set two columns that will stay in place no matter the screen resolution (col-xs-*
).
Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*
).
Finally, we shift the display order using the matching class (col-md-[push|pull]-*
). You push the first column over by the amount of the second, and pull the second by the amount of the first.
You can Try with
#python3
import hashlib
rawdata = "put your data here"
sha = hashlib.sha256(str(rawdata).encode("utf-8")).hexdigest() #For Sha256 hash
print(sha)
mdpass = hashlib.md5(str(sha).encode("utf-8")).hexdigest() #For MD5 hash
print(mdpass)
A simple getRowCount
method can look like this :
private int getRowCount(ResultSet resultSet) {
if (resultSet == null) {
return 0;
}
try {
resultSet.last();
return resultSet.getRow();
} catch (SQLException exp) {
exp.printStackTrace();
} finally {
try {
resultSet.beforeFirst();
} catch (SQLException exp) {
exp.printStackTrace();
}
}
return 0;
}
Just to be aware that this method will need a scroll sensitive resultSet
, so while creating the connection you have to specify the scroll option. Default is FORWARD and using this method will throw you exception.
I had this issue in HTML5 using CSS3 and my image was centered as such within the DIV... oh yes, I can't forget how I had to add the height to show the image... for a while I wondered where it was until I did this. I don't think the position and display are necessary.
background-image: url('../Images/01.png');
background-repeat:no-repeat;
background-position:center;
position:relative;
display:block;
height:60px;
Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.
Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:
Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:
[Users]
username = password
john = johns_password
steve = steves_password
In C:\svn_repos\my_repo\conf\svnserve.conf set:
[general]
password-db = passwd
auth-access=read
auth-access=write
This will force users to log in to read or write to this repository.
Follow these steps for each repository, only including the appropriate users in the passwd
file for each repository.
The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.
To return information, like your number, use
echo "$value"
To print additional information that you don't want captured, use
echo "my irrelevant info" >&2
Finally, to capture it, use what you did:
result=$(password_formula)
In other words:
echo "enter: "
read input
password_formula()
{
length=${#input}
last_two=${input:length-2:length}
first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
let sum=$first+$second
sum_len=${#sum}
echo $second >&2
echo $sum >&2
if [ $sum -gt 9 ]
then
sum=${sum:1}
fi
value=$second$sum$first
echo $value
}
result=$(password_formula)
echo "The value is $result"
You can wrap all tasks which can fail in block, and use ignore_errors: yes
with that block.
tasks:
- name: ls
command: ls -la
- name: pwd
command: pwd
- block:
- name: ls non-existing txt file
command: ls -la no_file.txt
- name: ls non-existing pic
command: ls -la no_pic.jpg
ignore_errors: yes
Read more about error handling in blocks here.
On Windows, check out BugTrap. Its not longer at the original link, but its still available on CodeProject.
According to https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1
If you expect that a blog post may exceed the 16Mb document limit, you should extract the comments into a separate collection and reference the blog post from the comment and do an application-level join.
// posts
[
{
_id: ObjectID('AAAA'),
text: 'a post',
...
}
]
// comments
[
{
text: 'a comment'
post: ObjectID('AAAA')
},
{
text: 'another comment'
post: ObjectID('AAAA')
}
]
Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.
Try something like:
secondViewController.view.backgroundColor = UIColor.redColor();
Now the view controller it shows should be red.
To actually do something with secondViewController
, create a subclass of UIViewController
and instead of
let secondViewController:UIViewController = UIViewController()
create an instance of your second view controller:
//If using code
let secondViewController = MyCustomViewController.alloc()
//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController
.NET XSLT implementation allows to write custom managed functions in the stylesheet. For lower-case() it can be:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<msxsl:script implements-prefix="utils" language="C#">
<![CDATA[
public string ToLower(string stringValue)
{
string result = String.Empty;
if(!String.IsNullOrEmpty(stringValue))
{
result = stringValue.ToLower();
}
return result;
}
]]>
</msxsl:script>
<!-- using of our custom function -->
<lowercaseValue>
<xsl:value-of select="utils:ToLower($myParam)"/>
</lowercaseValue>
Assume, that can be slow, but still acceptable.
Do not forget to enable embedded scripts support for transform:
// Create the XsltSettings object with script enabled.
XsltSettings xsltSettings = new XsltSettings(false, true);
XslCompiledTransform xslt = new XslCompiledTransform();
// Load stylesheet
xslt.Load(xsltPath, xsltSettings, new XmlUrlResolver());
As per HTML5, you can use
input type="datetime-local"
instead of
input type="date"
.
It will allow the [(ngModel)]
directive to read and write value from input control.
Note: If the date string contains 'Z' then to implement above solution, you need to trim the 'Z' character from date.
For more details, please go through this link on mozilla docs.
Here is an example Dockerfile leveraging several clever techniques to all you to run a full conda environment for every RUN
stanza. You can use a similar approach to execute any arbitrary prep in a script file.
Note: there is a lot of nuance when it comes to login/interactive vs nonlogin/noninteractive shells, signals, exec
, the way multiple args are handled, quoting, how CMD and ENTRYPOINT interact, and a million other things, so don't be discouraged if when hacking around with these things, stuff goes sideways. I've spent many frustrating hours digging through all manner of literature and I still don't quite get how it all clicks.
## Conda with custom entrypoint from base ubuntu image
## Build with e.g. `docker build -t monoconda .`
## Run with `docker run --rm -it monoconda bash` to drop right into
## the environment `foo` !
FROM ubuntu:18.04
## Install things we need to install more things
RUN apt-get update -qq &&\
apt-get install -qq curl wget git &&\
apt-get install -qq --no-install-recommends \
libssl-dev \
software-properties-common \
&& rm -rf /var/lib/apt/lists/*
## Install miniconda
RUN wget -nv https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh -O ~/miniconda.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm ~/miniconda.sh && \
/opt/conda/bin/conda clean -tipsy && \
ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh
## add conda to the path so we can execute it by name
ENV PATH=/opt/conda/bin:$PATH
## Create /entry.sh which will be our new shell entry point. This performs actions to configure the environment
## before starting a new shell (which inherits the env).
## The exec is important! This allows signals to pass
RUN (echo '#!/bin/bash' \
&& echo '__conda_setup="$(/opt/conda/bin/conda shell.bash hook 2> /dev/null)"' \
&& echo 'eval "$__conda_setup"' \
&& echo 'conda activate "${CONDA_TARGET_ENV:-base}"' \
&& echo '>&2 echo "ENTRYPOINT: CONDA_DEFAULT_ENV=${CONDA_DEFAULT_ENV}"' \
&& echo 'exec "$@"'\
) >> /entry.sh && chmod +x /entry.sh
## Tell the docker build process to use this for RUN.
## The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]
SHELL ["/entry.sh", "/bin/bash", "-c"]
## Now, every following invocation of RUN will start with the entry script
RUN conda update conda -y
## Create a dummy env
RUN conda create --name foo
## I added this variable such that I have the entry script activate a specific env
ENV CONDA_TARGET_ENV=foo
## This will get installed in the env foo since it gets activated at the start of the RUN stanza
RUN conda install pip
## Configure .bashrc to drop into a conda env and immediately activate our TARGET env
RUN conda init && echo 'conda activate "${CONDA_TARGET_ENV:-base}"' >> ~/.bashrc
ENTRYPOINT ["/entry.sh"]
$(".radioValue").css({"background-color":"-webkit-linear-gradient(#e9e9e9,rgba(255, 255, 255, 0.43137254901960786),#e9e9e9)","color":"#454545", "padding": "8px"});
myDate.ToString("yyyy-MM-dd HH:mm:ss")
the capital HH is for 24 hours format as you specified
The main difference is when the height of the elements are not the same! Then you can see how in the row, they are all center\end\start
I have a windows 7 and installing the ClickOnce Tools was not enough.
The signtool.exe
appeared after also installing the sdk:
One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)
add this to your css
.table-vcenter td {
vertical-align: middle!important;
}
then add to the class to your table:
<table class="table table-hover table-striped table-vcenter">
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:
view.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
Toast toast = Toast.makeText(
getApplicationContext(),
"View touched",
Toast.LENGTH_LONG
);
toast.show();
return true;
}
});
// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
downTime,
eventTime,
MotionEvent.ACTION_UP,
x,
y,
metaState
);
// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);
For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?
Follow these links for the MSDN descriptions of:
Math.Floor
, which rounds down towards negative infinity.Math.Ceiling
, which rounds up towards positive infinity.Math.Truncate
, which rounds up or down towards zero.Math.Round
, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)
" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)
" becoming 3).The following diagram and table may help:
-3 -2 -1 0 1 2 3
+--|------+---------+----|----+--|------+----|----+-------|-+
a b c d e
a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8
====== ====== ===== ===== =====
Floor -3 -1 0 1 2
Ceiling -2 0 1 2 3
Truncate -2 0 0 1 2
Round (ToEven) -3 0 0 2 3
Round (AwayFromZero) -3 -1 0 2 3
Note that Round
is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example:
n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15
With the other functions, you have to use multiply/divide trickery to achieve the same effect:
c = System.Math.Truncate (n * 100) / 100; // 3.14
d = System.Math.Ceiling (n * 100) / 100; // 3.15
The main disadvantage of the #define method is that the string is duplicated each time it is used, so you can end up with lots of copies of it in the executable, making it bigger.
All good answers from others. Here are two ways you can solve this:
Directly from the code where you will have to programmatically control the dimensions of the imageview
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
cell.imageView!.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
From the story board, where you can use the attribute inspector & size inspector in the utility pane to adjust positioning, add constraints and specify dimensions
In the storyboard, add an imageView object in to the cell's content view with your desired dimensions and add a tag to the view(imageView) in the attribute inspector. Then do the following in your viewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
let pictureView = cell.viewWithTag(119) as! UIImageView //let's assume the tag is set to 119
pictureView.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.
Just to update this answer for the sake of others who happen to end up on this page.
In Rails 3, you just need to create a file at views/users/show.json.erb
. The @user
object will be available to the view (just like it would be for html.) You don't even need to_json
anymore.
To summarize, it's just
# users contoller
def show
@user = User.find( params[:id] )
respond_to do |format|
format.html
format.json
end
end
and
/* views/users/show.json.erb */
{
"name" : "<%= @user.name %>"
}
My favorite pattern has become lately this:
var namespace = (function() {_x000D_
_x000D_
// expose to public_x000D_
return {_x000D_
a: internalA,_x000D_
c: internalC_x000D_
}_x000D_
_x000D_
// all private_x000D_
_x000D_
/**_x000D_
* Full JSDoc_x000D_
*/_x000D_
function internalA() {_x000D_
// ..._x000D_
}_x000D_
_x000D_
/**_x000D_
* Full JSDoc_x000D_
*/_x000D_
function internalB() {_x000D_
// ..._x000D_
}_x000D_
_x000D_
/**_x000D_
* Full JSDoc_x000D_
*/_x000D_
function internalC() {_x000D_
// ..._x000D_
}_x000D_
_x000D_
/**_x000D_
* Full JSDoc_x000D_
*/_x000D_
function internalD() {_x000D_
// ..._x000D_
}_x000D_
_x000D_
})();
_x000D_
Of course, return can be at the end, but if only function declarations follow it, it's much easier to see what's the namespace all about, and what API is exposed.
The pattern of using function expressions in such cases results in not being able to know what methods are exposed without going over the entire code.
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
what I've done is create a random color generator as many here have suggested
function dynamicColors() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgba(" + r + "," + g + "," + b + ", 0.5)";
}
and then coded this
var chartContext = document.getElementById('line-chart');
let lineChart = new Chart(chartContext, {
type: 'bar',
data : {
labels: <?php echo json_encode($names); ?>,
datasets: [{
data : <?php echo json_encode($salaries); ?>,
borderWidth: 1,
backgroundColor: dynamicColors,
}]
}
,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
maintainAspectRatio: false,
}
});
Notice there is no parantheses at the function call This enables the code to call the function every time, instead of making an array This also prevents the code from using the same color for all the bars
Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):
SELECT username, ip, time_stamp FROM (
SELECT username, ip, time_stamp,
ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
FROM Users
) tmp WHERE rn = 1;
Reversing string or any Array
(Stream.of("abcdefghijklm 1234567".split("")).collect(Collectors.collectingAndThen(Collectors.toList(),list -> {Collections.reverse(list);return list;}))).stream().forEach(System.out::println);
split can be modified based on the delimiter or space
load your url helper when you create a function eg,
visibility function_name () {
$this->load->helper('url');
}
the it will show you errors or a view you loaded.
You can write your query like so:
SELECT * FROM MyTable WHERE (A LIKE '%text1%' OR A LIKE '%text2%')
The %
is a wildcard, meaning that it searches for all rows where column A contains either text1 or text2
This was probably a casting issue
. Casting syntax
happens when you try to combine two different types of variables
. Since we cannot convert a string
to an integer
or float
always, we have to convert our integers
into a string
. This is how you do it.: str(x)
. To convert to a integer, it's: int(x)
, and a float is float(x)
. Our code will be:
print('Total score for ' + str(name) + ' is ' + str(score))
Also! Run this snippet
to see a table of how to convert different types of variables
!
<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>
_x000D_
It is a build target that is not a filename.
Here is an illustration of your first import cycle problem.
project/controllers/account
^ \
/ \
/ \
/ \/
project/components/mux <--- project/controllers/base
As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux
imports project/controllers/account
. Since Go does not support circular dependencies you get the import cycle not allowed
error during compile time.
Yes web application is much better than web sites, because Web applications give us freedom:
To have multiple projects under one umbrella and establish project dependencies between. E.g. for PCS we can have following within web application-
To run unit tests on code that is in the class files that are associated with ASP.NET pages
Assuming that both your directories are real Python packages (do have the __init__.py
file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.
I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.
import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# Use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if the script is called in different ways on Windows.
# __file__ fails if someone does os.chdir() before.
# sys.argv[0] also fails, because it doesn't not always contains the path.
As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.
Warning! I don't really know what is happening when current module is inside an egg
file. It probably fails too.
TL;DR
MySQL server might not be running after installation with Brew. Try brew services start mysql
or just mysql.server start
if you don't want MySQL to run as a background service.
Full Story:
I just installed MySQL (stable) 5.7.17 on a new MacBook Pro running Sierra and also got an error when running mysql_secure_installation
:
Securing the MySQL server deployment.
Enter password for user root:
Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Say what?
According to the installation info from Brew, mysql_secure_installation
should prompt me to... secure the installation. I figured the MySQL server might not be running and rightly so. Running brew services start mysql
and then mysql_secure_installation
worked like a charm.
QUESTION was: suppose T john is to be converted john T, how to change in excel?
If text "T john" is in cell A1
=CONCATENATE(RIGHT(A1,LEN(A1)-2)," ",LEFT(A1,1))
and with a nod to the & crowd
=RIGHT(A1,LEN(A1)-2)&" "&LEFT(A1,1)
takes the right part of the string excluding the first 2 characters, adds a space, adds the first character.
NSDictionary from NSData
http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/
NSDictionary to NSData
You can use NSPropertyListSerialization class for that. Have a look at its method:
+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString
Returns an NSData object containing a given property list in a specified format.
Inside class definitions you can only declare static members. They have to be defined outside of the class. For compile-time integral constants the standard makes the exception that you can "initialize" members. It's still not a definition, though. Taking the address would not work without definition, for example.
I'd like to mention that I don't see the benefit of using std::string over const char[] for constants. std::string is nice and all but it requires dynamic initialization. So, if you write something like
const std::string foo = "hello";
at namespace scope the constructor of foo will be run right before execution of main starts and this constructor will create a copy of the constant "hello" in the heap memory. Unless you really need RECTANGLE to be a std::string you could just as well write
// class definition with incomplete static member could be in a header file
class A {
static const char RECTANGLE[];
};
// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";
There! No heap allocation, no copying, no dynamic initialization.
Cheers, s.
You can't do it with pure html/javascript. This is because you have a seperate connection to the webserver to retrieve a separate file (the image) and a normal webserver will serve the file with content headers set so that the browser reading the content type will decide that the type can be handled internally.
The way to force the browser not to handle the file internally is to change the headers (content-disposition prefereably, or content-type) so the browser will not try to handle the file internally. You can either do this by writing a script on the webserver that dynamically sets the headers (i.e. download.php) or by configuring the webserver to return different headers for the file you want to download. You can do this on a per-directory basis on the webserver, which would allow you to get away without writing any php or javascript - simply have all your download images in that one location.
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid;
border-collapse: collapse;
}
td , th {
padding: 5px;
width: 100px;
}
th {
background-color: lightgreen;
}
</style>
</head>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort car objects on age.</p>
<p id="demo"></p>
<script>
var nameArrow = "", yearArrow = "";
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
yearACS = true;
function sortYear() {
if (yearACS) {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
return a.year - b.year;
});
yearACS = false;
}else {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
return b.year - a.year;
});
yearACS = true;
}
displayCars();
}
nameACS = true;
function sortName() {
if (nameACS) {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
x = a.type.toLowerCase();
y = b.type.toLowerCase();
if (x > y) {return 1;}
if (x < y) {return -1};
return 0;
});
nameACS = false;
} else {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
x = a.type.toUpperCase();
y = b.type.toUpperCase();
if (x > y) { return -1};
if (x <y) { return 1 };
return 0;
});
nameACS = true;
}
displayCars();
}
displayCars();
function displayCars() {
var txt = "<table><tr><th onclick='sortName()'>name " + nameArrow + "</th><th onclick='sortYear()'>year " + yearArrow + "</th><tr>";
for (let i = 0; i < cars.length; i++) {
txt += "<tr><td>"+ cars[i].type + "</td><td>" + cars[i].year + "</td></tr>";
}
txt += "</table>";
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
_x000D_
Error 1064 often occurs when missing DELIMITER around statement like : create function, create trigger.. Make sure to add DELIMITER $$ before each statement and end it with $$ DELIMITER like this:
DELIMITER $$
CREATE TRIGGER `agents_before_ins_tr` BEFORE INSERT ON `agents`
FOR EACH ROW
BEGIN
END $$
DELIMITER ;
You should mention the library on the command line after the object files being compiled:
gcc -Wstrict-prototypes -Wall -Wno-sign-compare -Wpointer-arith -Wdeclaration-after-statement -Wformat-security -Wswitch-enum -Wunused-parameter -Wstrict-aliasing -Wbad-function-cast -Wcast-align -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-field-initializers -Wno-override-init \
-g -O2 -export-dynamic -o utilities/ovs-dpctl utilities/ovs-dpctl.o \
lib/libopenvswitch.a \
/home/jyyoo/src/dpdk/build/lib/librte_eal.a /home/jyyoo/src/dpdk/build/lib/libethdev.a /home/jyyoo/src/dpdk/build/lib/librte_cmdline.a /home/jyyoo/src/dpdk/build/lib/librte_hash.a /home/jyyoo/src/dpdk/build/lib/librte_lpm.a /home/jyyoo/src/dpdk/build/lib/librte_mbuf.a /home/jyyoo/src/dpdk/build/lib/librte_ring.a /home/jyyoo/src/dpdk/build/lib/librte_mempool.a /home/jyyoo/src/dpdk/build/lib/librte_malloc.a \
-lrt -lm -lpthread
Explanation: the linking is dependent on the order of modules. Symbols are first requested, and then linked in from a library that has them. So you have to specify modules that use libraries first, and libraries after them. Like this:
gcc x.o y.o z.o -la -lb -lc
Moreover, in case there's a circular dependency, you should specify the same library on the command line several times. So in case libb
needs symbol from libc
and libc
needs symbol from libb
, the command line should be:
gcc x.o y.o z.o -la -lb -lc -lb
Atomic size is 4096 bytes, max size is 65536 bytes. Sendfile uses 16 pipes each of 4096 bytes size. cmd : ioctl(fd, FIONREAD, &buff_size).
The CSV format sounds easy enough for StringTokenizer but it can become more complicated. Here in Germany a semicolon is used as a delimiter and cells containing delimiters need to be escaped. You're not going to handle that easily with StringTokenizer.
I would go for http://sourceforge.net/projects/javacsv
Downgrading the iOS development Target from 12.1
to 12
fix the issue for me as I don't have a dev team configured.
Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.
In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.
Try recompiling your code with Java 1.7 or upgrade your Java Plugin.
You can also set your div with the following:
#something {width: 400px; margin: auto;}
With that setting, the div will have a set width, and the margin and either side will automatically set depending on the with of the browser.
For me the solution was in setting the global variable path to the JDK. See here: https://appopus.wordpress.com/2012/07/11/how-to-install-jdk-java-development-kit-and-jarsigner-on-windows/
In Python 3.6+ you could use Variable Annotations for this:
https://www.python.org/dev/peps/pep-0526/#abstract
PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:
# 'captain' is a string (Note: initial value is a problem)
captain = ... # type: str
PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:
captain: str # Note: no initial value!
It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"