One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)
taking @rijul's answer forward, it doesn't work in marshmallow and above versions:
//for pre-marshmallow versions
String path = System.getenv("SECONDARY_STORAGE");
// For Marshmallow, use getExternalCacheDirs() instead of System.getenv("SECONDARY_STORAGE")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
File[] externalCacheDirs = mContext.getExternalCacheDirs();
for (File file : externalCacheDirs) {
if (Environment.isExternalStorageRemovable(file)) {
// Path is in format /storage.../Android....
// Get everything before /Android
path = file.getPath().split("/Android")[0];
break;
}
}
}
// Android avd emulator doesn't support this variable name so using other one
if ((null == path) || (path.length() == 0))
path = Environment.getExternalStorageDirectory().getAbsolutePath();
As described in Documentation Environment.getExternalStorageDirectory() :
Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.
This is an example of how to use it reading an image :
String fileName = "stored_image.jpg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";
File f = new File(pathDir + File.separator + fileName);
if(f.exists()){
Log.d("Application", "The file " + file.getName() + " exists!";
}else{
Log.d("Application", "The file no longer exists!";
}
I had an application that used a ListPreference
where the user was required to select the location of where they wanted to save something.
In that app, I scanned /proc/mounts
and /system/etc/vold.fstab
for sdcard mount points. I stored the mount points from each file into two separate ArrayList
s.
Then, I compared one list with the other and discarded items that were not in both lists. That gave me a list of root paths to each sdcard.
From there, I tested the paths with File.exists()
, File.isDirectory()
, and File.canWrite()
. If any of those tests were false, I discarded that path from the list.
Whatever was left in the list, I converted to a String[]
array so it could be used by the ListPreference
values attribute.
You can view the code here: http://sapienmobile.com/?p=204
There is a Headers
property in the HttpRequestMessage
class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders
in the HttpClient
class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.
Hope this makes things more clear, at least for someone seeing this answer in future.
If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.
Here the script that can remove up to 12 commas:
function uncomma(x) {
var string1 = x;
for (y = 0; y < 12; y++) {
string1 = string1.replace(/\,/g, '');
}
return string1;
}
Modify that for loop if you need bigger numbers.
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
All JSON.parse
implementations most likely use eval()
JSON.parse
is based on Douglas Crockford's solution, which uses eval()
right there on line 497.
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
The advantage of JSON.parse
is that it verifies the argument is correct JSON syntax.
I describe here a problem that I faced when run npm install
- the package does not appear in node_modules
.
The issue was that the name
value in package.json
of installed package was different than the name of imported package (key in package.json
of my project).
So if your installed project name is some-package
(name value in its package.json
) then
in package.json
of your project write: "some-package": "owner/some-repo#tag"
.
using (FileStream fs = File.OpenRead(binarySourceFile.Path))
using (BinaryReader reader = new BinaryReader(fs))
{
// Read in all pairs.
while (reader.BaseStream.Position != reader.BaseStream.Length)
{
Item item = new Item();
item.UniqueId = reader.ReadString();
item.StringUnique = reader.ReadString();
result.Add(item);
}
}
return result;
Make sure that you have php-xml module installed and enabled in php.ini
.
You can also change response format to json which is easier to handle. In that case you have to only add &format=json
to url query string.
$rest_url = "http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls=".urlencode($source_url);
And then use json_decode()
to retrieve data in your script:
$result = json_decode($content, true);
$fb_like_count = $result['like_count'];
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
Also you can add <br> instead of \n.
And then you can add text to TexView:
articleTextView.setText(Html.fromHtml(textForTextView));
If you don't care about the order, just do this:
def remove_duplicates(l):
return list(set(l))
A set
is guaranteed to not have duplicates.
OK, if that's what you want, here's what I would do to fix your existing code:
from collections import Counter
def count_letters(words):
counter = Counter()
for word in words.split():
counter.update(word)
return sum(counter.itervalues())
words = "The grey old fox is an idiot"
print count_letters(words) # 22
If you don't want to count certain non-whitespace characters, then you'll need to remove them -- inside the for
loop if not sooner.
Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http
it returns observable instead of promise, like you did
return this.http
.get(this.configEndPoint)
.map(res => res.json());
then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()
.map() is used to convert the observable (received from http request)to any form like .json(), .text()
as stated in Angular's official website,
.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view
this.myService.getConfig().subscribe(res => {
console.log(res);
this.data = res;
});
Besides the "accented letters are sorted differently than unaccented ones" in some Western European languages, you must take into account the groups of letters, which sometimes are sorted differently, also.
Traditionally, in Spanish, "ch" was considered a letter in its own right, same with "ll" (both of which represent a single phoneme), so a list would get sorted like this:
Notice all the words starting with single c go together, except words starting with ch which go after them, same with ll-starting words which go after all the words starting with a single l. This is the ordering you'll see in old dictionaries and encyclopedias, sometimes even today by very conservative organizations.
The Royal Academy of the Language changed this to make it easier for Spanish to be accomodated in the computing world. Nevertheless, ñ is still considered a different letter than n and goes after it, and before o. So this is a correctly ordered list:
By selecting the correct collation, you get all this done for you, automatically :-)
This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('/tmp/test.png')
EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show()
when you are ready to display the plots:
import matplotlib.pyplot as plt
# Turn interactive plotting off
plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')
# Display all "open" (non-closed) figures
plt.show()
This is how you can do it-
HTML-
<div style="overflow:hidden; height:100%">
<div style="float:left">a<br>b</div>
<table cellpadding="0" cellspacing="0" style="height:100%;">
<tr><td>This is the content of a table that takes 100% height</td></tr>
</table>
</div>
CSS-
html,body
{
height:100%;
background-color:grey;
}
table
{
background-color:yellow;
}
See the DEMO
Update: Well, if you are not looking for applying 100% height to your parent containers, then here is a jQuery solution that should help you-
Script-
$(document).ready(function(){
var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
$("#tab").css("height",b);
});
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is better than inserting code into python that asks you to press any key - because if the program crashes before it reaches that point, the window closes and you lose the crash info. The solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat"
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
HTML link click
<a class="download" href="{{route('project.download',$post->id)}}">DOWNLOAD</a>
// Route
Route::group(['middleware'=>['auth']], function(){
Route::get('file-download/{id}', 'PostController@downloadproject')->name('project.download');
});
public function downloadproject($id) {
$book_cover = Post::where('id', $id)->firstOrFail();
$path = public_path(). '/storage/uploads/zip/'. $book_cover->zip;
return response()->download($path, $book_cover
->original_filename, ['Content-Type' => $book_cover->mime]);
}
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
The following snippet solved the issue for me:
class FigureWrapper(object):
'''Frees underlying figure when it goes out of scope.
'''
def __init__(self, figure):
self._figure = figure
def __del__(self):
plt.close(self._figure)
print("Figure removed")
# .....
f, ax = plt.subplots(1, figsize=(20, 20))
_wrapped_figure = FigureWrapper(f)
ax.plot(...
plt.savefig(...
# .....
When _wrapped_figure
goes out of scope the runtime calls our __del__()
method with plt.close()
inside. It happens even if exception fires after _wrapped_figure
constructor.
▐▐ is HTML and is made with this code: ▐▐
.
I've tried using the autoplay tag, and .load() .play() still need to be called at least in chrome (maybe its my settings).
the simplest cross browser way to do this with jquery using your example would be
var $video = $('#divVideo video'),
videoSrc = $('source', $video).attr('src', videoFile);
$video[0].load();
$video[0].play();
However the way I'd suggest you do it (for legibility and simplicity) is
var video = $('#divVideo video')[0];
video.src = videoFile;
video.load();
video.play();
Further Reading http://msdn.microsoft.com/en-us/library/ie/hh924823(v=vs.85).aspx#ManagingPlaybackInJavascript
Additional info: .load() only works if there is an html source element inside the video element (i.e. <source src="demo.mp4" type="video/mp4" />
)
The non jquery way would be:
HTML
<div id="divVideo">
<video id="videoID" controls>
<source src="test1.mp4" type="video/mp4" />
</video>
</div>
JS
var video = document.getElementById('videoID');
video.src = videoFile;
video.load();
video.play();
A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.
public class ListModel<T>
{
public List<T> Items { get; set; }
public ListModel(List<T> list) {
Items = list;
}
}
and when you return the View you just need to simply do:
List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));
then define the list in the model:
@model ListModel<customClass>
and ready to go:
@foreach(var element in Model.Items) {
//do as needed...
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
This is quite simple.
Assuming the data is stored in a column called A in a table called T, you can use
select A, count(A) from T group by A
A little more elegant way of doing the same adding on to the above comment ..
<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
AutoGenerateColumns="false"
OnRowDeleting="deleteRow"
GridLines="Vertical">
<asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
<asp:BoundField DataField="EntityId" HeaderText="EntityId" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lnkCustomize" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>' runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
And on the server side:
protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
string IdTemplate= e.Values["IdTemplate"].ToString();
string EntityId = e.Values["EntityId"].ToString();
// Do stuff..
}
Collections.reverse(Arrays.asList(yourArray));
java.util.Collections.reverse()
can reverse java.util.List
s and java.util.Arrays.asList()
returns a list that wraps the the specific array you pass to it, therefore yourArray
is reversed after the invocation of Collections.reverse()
.
The cost is just the creation of one List-object and no additional libraries are required.
A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
You can just add the number to the cell with the date.
so if A1: 12/3/2012
and A2: =A1+7
then A2 would display 12/10/2012
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'
Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.
I am the author of https://github.com/joonhocho/seri.
Seri is JSON + custom (nested) class support.
You simply need to provide toJSON
and fromJSON
to serialize and deserialize any class instances.
Here's an example with nested class objects:
import seri from 'seri';
class Item {
static fromJSON = (name) => new Item(name)
constructor(name) {
this.name = name;
}
toJSON() {
return this.name;
}
}
class Bag {
static fromJSON = (itemsJson) => new Bag(seri.parse(itemsJson))
constructor(items) {
this.items = items;
}
toJSON() {
return seri.stringify(this.items);
}
}
// register classes
seri.addClass(Item);
seri.addClass(Bag);
const bag = new Bag([
new Item('apple'),
new Item('orange'),
]);
const bagClone = seri.parse(seri.stringify(bag));
// validate
bagClone instanceof Bag;
bagClone.items[0] instanceof Item;
bagClone.items[0].name === 'apple';
bagClone.items[1] instanceof Item;
bagClone.items[1].name === 'orange';
Hope it helps address your problem.
Update 1 November 2012
My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr()
to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with his recommendation to prefer attr()
.
Original answer
If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.
I'll summarize the main issues:
prop()
rather than attr()
.prop()
does what attr()
used to do. Replacing calls to attr()
with prop()
in your code will generally work.checked
property is a Boolean, the style
property is an object with individual properties for each style, the size
property is a number.value
and checked
: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue
/ defaultChecked
property).If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.
As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:
<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">
So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:
if ( $("#cb").attr("checked") === true ) {...}
if ( $("#cb").attr("checked") == "checked" ) {...}
if ( $("#cb").is(":checked") ) {...}
This is actually the simplest thing in the world to do with the checked
Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:
if (document.getElementById("cb").checked) {...}
The property also makes checking or unchecking the checkbox trivial:
document.getElementById("cb").checked = false
In jQuery 1.6, this unambiguously becomes
$("#cb").prop("checked", false)
The idea of using the checked
attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.
checked
attributei want to show records only starting with b
select name from user where name LIKE 'b%';
i am trying to sort MySQL data alphabeticaly
select name from user ORDER BY name;
i am trying to sort MySQL data in reverse alphabetic order
select name from user ORDER BY name desc;
input[type="text"]
{
background: transparent;
border: none;
}
Nobody will even know it's there.
@QueryMap
worked for me instead of FieldMap
If you have a bunch of GET params, another way to pass them into your url is a HashMap
.
class YourActivity extends Activity {
private static final String BASEPATH = "http://www.example.com";
private interface API {
@GET("/thing")
void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
API service = rest.create(API.class);
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "val1");
params.put("key2", "val2");
// ... as much as you need.
service.getMyThing(params, new Callback<String>() {
// ... do some stuff here.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
simple synchronous way with node:
let fs = require('fs')
let filename = "your-file.something"
let content = fs.readFileSync(process.cwd() + "/" + filename).toString()
console.log(content)
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
DISTINCT
removes rows if all selected values are equal. Apparently, you have entries with the same p.id
but with different pl.nm
(or pl.val
or pl.txt_val
). The answer to your question depends on which one of these values you want to show in the one row with your p.id
(the first? the smallest? any?).
When doing a getObject()
from the S3 API, per the docs the contents of your file are located in the Body
property, which you can see from your sample output. You should have code that looks something like the following
const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary
var getParams = {
Bucket: 'abc', // your bucket name,
Key: 'abc.txt' // path to the object you're looking for
}
s3.getObject(getParams, function(err, data) {
// Handle any error and exit
if (err)
return err;
// No error happened
// Convert Body from a Buffer to a String
let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});
You may not need to create a new buffer from the data.Body
object but if you need you can use the sample above to achieve that.
"crypto/rand" is cross platform pkg for random bytes generattion
package main
import (
"crypto/rand"
"fmt"
)
// Note - NOT RFC4122 compliant
func pseudo_uuid() (uuid string) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
fmt.Println("Error: ", err)
return
}
uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return
}
If you don't want the overhead of WindowManagers, Points, or Displays, you can grab the height and width attributes of the topmost View item in your XML, provided its height and width are set to match_parent. (This is true so long as your layout takes up the entire screen.)
For example, if your XML starts with something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/entireLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
Then findViewById(R.id.entireLayout).getWidth()
will return the screen's width and findViewById(R.id.entireLayout).getHeight()
will return the screen's height.
these code is converted code from gbk answer in swift 4
1.in your main controllview :
if let filePath = Bundle.main.path(forResource: "clip", ofType: "mp4") {
let fileURL = NSURL(fileURLWithPath: filePath)
videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
if let player = videoPlayer {
player.playerRate = 1.00
}
}
you need VideoPlayer class
import AVFoundation
import Foundation
protocol VideoPlayerDelegate {
func downloadedProgress(progress:Double)
func readyToPlay()
func didUpdateProgress(progress:Double)
func didFinishPlayItem()
func didFailPlayToEnd()
}
let videoContext:UnsafeMutablePointer<Void>? = nil
class VideoPlayer : NSObject {
private var assetPlayer:AVPlayer?
private var playerItem:AVPlayerItem?
private var urlAsset:AVURLAsset?
private var videoOutput:AVPlayerItemVideoOutput?
private var assetDuration:Double = 0
private var playerView:PlayerView?
private var autoRepeatPlay:Bool = true
private var autoPlay:Bool = true
var delegate:VideoPlayerDelegate?
var playerRate:Float = 1 {
didSet {
if let player = assetPlayer {
player.rate = playerRate > 0 ? playerRate : 0.0
}
}
}
var volume:Float = 0 {
didSet {
if let player = assetPlayer {
player.volume = 50
}
}
}
// MARK: - Init
convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
self.init()
playerView = view
autoPlay = startAutoPlay
autoRepeatPlay = repeatAfterEnd
if let playView = playerView{
if let playerLayer = playView.layer as? AVPlayerLayer {
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
}
}
initialSetupWithURL(url: urlAsset)
prepareToPlay()
}
override init() {
super.init()
}
// MARK: - Public
func isPlaying() -> Bool {
if let player = assetPlayer {
return player.rate > 0
} else {
return false
}
}
func seekToPosition(seconds:Float64) {
if let player = assetPlayer {
pause()
if let timeScale = player.currentItem?.asset.duration.timescale {
player.seek(to: CMTimeMakeWithSeconds(seconds, timeScale), completionHandler: { (complete) in
self.play()
})
}
}
}
func pause() {
if let player = assetPlayer {
player.pause()
}
}
func play() {
if let player = assetPlayer {
if (player.currentItem?.status == .readyToPlay) {
player.play()
player.rate = playerRate
}
}
}
func cleanUp() {
if let item = playerItem {
item.removeObserver(self, forKeyPath: "status")
item.removeObserver(self, forKeyPath: "loadedTimeRanges")
}
NotificationCenter.default.removeObserver(self)
assetPlayer = nil
playerItem = nil
urlAsset = nil
}
// MARK: - Private
private func prepareToPlay() {
let keys = ["tracks"]
if let asset = urlAsset {
asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
DispatchQueue.global(qos: .userInitiated).async {
// Bounce back to the main thread to update the UI
DispatchQueue.main.async {
self.startLoading()
}
}
})
}
}
private func startLoading(){
var error:NSError?
guard let asset = urlAsset else {return}
// let status:AVKeyValueStatus = asset.statusOfValueForKey("tracks", error: &error)
let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: nil)
if status == AVKeyValueStatus.loaded {
assetDuration = CMTimeGetSeconds(asset.duration)
let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
playerItem = AVPlayerItem(asset: asset)
if let item = playerItem {
item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name:NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
if let output = videoOutput {
item.add(output)
item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
assetPlayer = AVPlayer(playerItem: item)
if let player = assetPlayer {
player.rate = playerRate
}
addPeriodicalObserver()
if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
layer.player = assetPlayer
}
}
}
}
}
private func addPeriodicalObserver() {
let timeInterval = CMTimeMake(1, 1)
if let player = assetPlayer {
player.addPeriodicTimeObserver(forInterval: timeInterval, queue:
DispatchQueue.main
, using: { (time) in
self.playerDidChangeTime(time: time)
})
}
}
private func playerDidChangeTime(time:CMTime) {
if let player = assetPlayer {
let timeNow = CMTimeGetSeconds(player.currentTime())
let progress = timeNow / assetDuration
delegate?.didUpdateProgress(progress: progress)
}
}
@objc private func playerItemDidReachEnd() {
delegate?.didFinishPlayItem()
if let player = assetPlayer {
player.seek(to: kCMTimeZero)
if autoRepeatPlay == true {
play()
}
}
}
@objc private func didFailedToPlayToEnd() {
delegate?.didFailPlayToEnd()
}
private func playerDidChangeStatus(status:AVPlayerStatus) {
if status == .failed {
print("Failed to load video")
} else if status == .readyToPlay, let player = assetPlayer {
volume = player.volume
delegate?.readyToPlay()
if autoPlay == true && player.rate == 0.0 {
play()
}
}
}
private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
var maximum:TimeInterval = 0
for value in ranges {
let range:CMTimeRange = value.timeRangeValue
let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
if currentLoadedTimeRange > maximum {
maximum = currentLoadedTimeRange
}
}
let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
delegate?.downloadedProgress(progress: progress)
}
deinit {
cleanUp()
}
private func initialSetupWithURL(url:NSURL) {
let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
// urlAsset = AVURLAsset(URL: url, options: options)
urlAsset = AVURLAsset(url: url as URL, options: options)
}
// MARK: - Observations
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?){
if (context as? UnsafeMutablePointer<Void> ) == videoContext {
if let key = keyPath {
if key == "status", let player = assetPlayer {
playerDidChangeStatus(status: player.status)
} else if key == "loadedTimeRanges", let item = playerItem {
moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
}
}
}
}
}
and a PlayerView class to create a videoview:
import AVFoundation
import UIKit
class PlayerView: UIView {
override class var layerClass: AnyClass {
get {
return AVPlayerLayer.self
}
}
var player:AVPlayer? {
set {
if let layer = layer as? AVPlayerLayer {
layer.player = player
}
}
get {
if let layer = layer as? AVPlayerLayer {
return layer.player
} else {
return nil
}
}
}
}
Install List::MoreUtils from CPAN
Then in your code:
use strict;
use warnings;
use List::MoreUtils qw(uniq);
my @dup_list = qw(1 1 1 2 3 4 4);
my @uniq_list = uniq(@dup_list);
Yes, if you redirect the output, it won't appear on the console. Use tee
.
ls 2>&1 | tee /tmp/ls.txt
On top of dhobbs answer above (https://stackoverflow.com/a/9728478/624597), here is an extra functionality of storing results to a file (I personally use it to copy and paste to FreeMind to have a nice overview of the structure, therefore I used tabs instead of spaces for indentation):
import os
def list_files(startpath):
with open("folder_structure.txt", "w") as f_output:
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = '\t' * 1 * (level)
output_string = '{}{}/'.format(indent, os.path.basename(root))
print(output_string)
f_output.write(output_string + '\n')
subindent = '\t' * 1 * (level + 1)
for f in files:
output_string = '{}{}'.format(subindent, f)
print(output_string)
f_output.write(output_string + '\n')
list_files(".")
Another way of doing it. This approach can be useful for changing the text to 2 different colors, just by adding 2 spans.
Label1.Text = "String with original color" + "<b><span style=""color:red;"">" + "Your String Here" + "</span></b>";
XMLStarlet or another XPath engine is the correct tool for this job.
For instance, with data.xml
containing the following:
<root>
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
</item>
</root>
...you can extract only the first title with the following:
xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml
Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster & Jobs
to Brewster & Jobs
), and so forth.
Here is a basic hover example.
Component's template property:
Template
<!-- attention, we have the c_highlight class -->
<!-- c_highlight is the selector property value of the directive -->
<p class="c_highlight">
Some text.
</p>
And our directive
import {Component,HostListener,Directive,HostBinding} from '@angular/core';
@Directive({
// this directive will work only if the DOM el has the c_highlight class
selector: '.c_highlight'
})
export class HostDirective {
// we could pass lots of thing to the HostBinding function.
// like class.valid or attr.required etc.
@HostBinding('style.backgroundColor') c_colorrr = "red";
@HostListener('mouseenter') c_onEnterrr() {
this.c_colorrr= "blue" ;
}
@HostListener('mouseleave') c_onLeaveee() {
this.c_colorrr = "yellow" ;
}
}
Did you maybe use some <tab>
instead of spaces?
Try remove all the spaces before the code and readd them using <space>
characters, just to be sure it's not a <tab>
.
In the POSIX standard, which /bin/sh
is supposed to respect, the command is .
(a single dot), not source
. The source
command is a csh
-ism that has been pulled into bash
.
Try
. $env_name/bin/activate
Or if you must have non-POSIX bash
-isms in your code, use #!/bin/bash
.
You can refresh the Python shell by pressing f5, or go to Run-> Run Module. This way you don't have to change the directory to read something from the file. Python will automatically change the directory. But if you want to work with different files from different directory in the Python Shell, then you can change the directory in sys, as Cameron said earlier.
It's easier to use the timestamp for this things since Tweepy gets both
import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
I couldn't find anything that met my requirements, hece I came up with this script (depends on jQuery):
https://gist.github.com/invernizzie/95182de86ea9dc5daa80
It will resize the iframe to the viewport size (taking into account wider content). It could use an improvement to use the viewport height instead of the content height, in the case that the former is bigger.
How about plain JavaScript? More about Array.prototype.filter()
.
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
This is certainly something that has a lot of traps. I was working with Paolo Bergantino's answer, and realising that even that has some limitations. I found working with string representations of dates a good place to quickly find some of the main problems. Start with an input string like this:
'12-2-2019 5:1:48.670'
and set up Paolo's function like this:
function count(re, str) {
if (typeof re !== "string") {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
var cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
I wanted the regular expression to be passed in, so that the function is more reusable, secondly, I wanted the parameter to be a string, so that the client doesn't have to make the regex, but simply match on the string, like a standard string utility class method.
Now, here you can see that I'm dealing with issues with the input. With the following:
if (typeof re !== "string") {
return 0;
}
I am ensuring that the input isn't anything like the literal 0
, false
, undefined
, or null
, none of which are strings. Since these literals are not in the input string, there should be no matches, but it should match '0'
, which is a string.
With the following:
re = (re === '.') ? ('\\' + re) : re;
I am dealing with the fact that the RegExp constructor will (I think, wrongly) interpret the string '.'
as the all character matcher \.\
Finally, because I am using the RegExp constructor, I need to give it the global 'g'
flag so that it counts all matches, not just the first one, similar to the suggestions in other posts.
I realise that this is an extremely late answer, but it might be helpful to someone stumbling along here. BTW here's the TypeScript version:
function count(re: string, str: string): number {
if (typeof re !== 'string') {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
const cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
If you need to get quantity of selected checkboxes:
var selected = []; // initialize array
$('div#checkboxes input[type=checkbox]').each(function() {
if ($(this).is(":checked")) {
selected.push($(this));
}
});
var selectedQuantity = selected.length;
Div is a block element and span is an inline element and its width depends upon the content of it self where div does not
via Is there a way to link someone to a YouTube Video in HD 1080p quality?
Yes there is:
https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720
options are:
default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;
As mentioned, you have to use the /embed/
or /v/
URL.
Note: Some copyrighted content doesn't support be played in this way
System.Environment.MachineName
Or, if you are using Winforms, you can use System.Windows.Forms.SystemInformation.ComputerName
, which returns exactly the same value as System.Environment.MachineName
.
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory
I gues there are too many keys in the counter
dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.
To save it, don't create a giant object, e.g. the counter.
1.StackOverflow
a program that create too many local variables.
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
... f.write('\tx%d = %d\n' % (x, x))
...
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed
2.OutOfMemory
a program that creats a giant dict
includes too many keys.
>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
... f.write('counter[%d] = %d\n' % (x, x))
...
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
h3 is absolutly a better solution than h2, h1 or h6 !
You have to use specific level : if you're in a h1, use h2, if you're in a h5, use h6 (if you're in a h6... hum, use strong or em for exemple). It not a obligation but a question of accessibility (Here, green part).
You don't have to give title to list... because this element it doesn't exist. So screen reader will not use something special.
Therefore, using Hn is probably one of the best solution, but surely not a specific level.
Try this,
$('.popup').click(function(event) {
event.preventDefault();
window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
});
You have to include jQuery reference to work this, here is the working sampe http://jsfiddle.net/a7qJt/
Constructor: The constructor method on an ES6 class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It’s out of Angular’s control when the constructor is invoked, which means that it’s not a suitable hook to let you know when Angular has finished initialising the component. JavaScript engine calls the constructor, not Angular directly. Which is why the ngOnInit (and $onInit in AngularJS) lifecycle hook was created. Bearing this in mind, there is a suitable scenario for using the constructor. This is when we want to utilise dependency injection - essentially for “wiring up” dependencies into the component.
As the constructor is initialised by the JavaScript engine, and TypeScript allows us to tell Angular what dependencies we require to be mapped against a specific property.
ngOnInit is purely there to give us a signal that Angular has finished initialising the component.
This phase includes the first pass at Change Detection against the properties that we may bind to the component itself - such as using an @Input() decorator.
Due to this, the @Input() properties are available inside ngOnInit, however are undefined inside the constructor, by design
I agree with japollock way up there--throw an acception when you are uncertain about the outcome of an operation. Calls to APIs, accessing filesystems, database calls, etc. Anytime you are moving past the "boundaries" of your programming languages.
I'd like to add, feel free to throw a standard exception. Unless you are going to do something "different" (ignore, email, log, show that twitter whale picture thingy, etc), then don't bother with custom exceptions.
You have a parent element, you want to get all child of specific attribute
1. get the parent
2. get the parent nodename by using parent.nodeName.toLowerCase()
convert the nodename to lower case e.g DIV will be div
3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id")
. this will give you id
of the parent
4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " );
if you want input children of the parent node
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
parent_clas_arr.forEach(e=>{_x000D_
parent_clas_str +=e+'.';_x000D_
})_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1) //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
You need to float all the buttons to left and make sure its width to fit within outer container.
CSS:
.btn{
float:left;
}
HTML:
<button type="submit" class="btn" onClick="return false;" >Save</button>
<button type="submit" class="btn" onClick="return false;">Publish</button>
<button class="btn">Back</button>
I think $PsHome has the information you're after?
PS .> $PsHome C:\Windows\System32\WindowsPowerShell\v1.0 PS .> Get-Help about_automatic_variables TOPIC about_Automatic_Variables ...
I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.
In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.
[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]
angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
return $resource('makes.json', {}, {
query: {method:'GET', isArray:true}
});
});
<div ng:controller="MakeModelCtrl">
<div>Make</div>
<select id="makeListBox"
ng-model="make.selected"
ng-options="make.code as make.name for make in makes"
ng-change="makeChanged(make.selected)">
</select>
<div>Model</div>
<select id="modelListBox"
ng-disabled="makeNotSelected"
ng-model="model.selected"
ng-options="model.code as model.name for model in models">
</select>
</div>
function MakeModelCtrl($scope)
{
$scope.makeNotSelected = true;
$scope.make = {selected: "0"};
$scope.makes = Make.query({}, function (makes) {
$scope.make = {selected: makes[0].code};
});
$scope.makeChanged = function(selectedMakeCode) {
$scope.makeNotSelected = !selectedMakeCode;
if ($scope.makeNotSelected)
{
$scope.model = {selected: "0"};
}
};
$scope.models = [
{code:"0", name:"Select Model"},
{code:"1", name:"Model1"},
{code:"2", name:"Model2"}
];
$scope.model = {selected: "0"};
}
As an extension method
public static IEnumerable<TSource> AreNotEqual<TSource, TKey, TTarget>(this IEnumerable<TSource> source, Func<TSource, TKey> sourceKeySelector, IEnumerable<TTarget> target, Func<TTarget, TKey> targetKeySelector)
{
var targetValues = new HashSet<TKey>(target.Select(targetKeySelector));
return source.Where(sourceValue => targetValues.Contains(sourceKeySelector(sourceValue)) == false);
}
eg.
public class Customer
{
public int CustomerId { get; set; }
}
public class OtherCustomer
{
public int Id { get; set; }
}
var customers = new List<Customer>()
{
new Customer() { CustomerId = 1 },
new Customer() { CustomerId = 2 }
};
var others = new List<OtherCustomer>()
{
new OtherCustomer() { Id = 2 },
new OtherCustomer() { Id = 3 }
};
var result = customers.AreNotEqual(customer => customer.CustomerId, others, other => other.Id).ToList();
Debug.Assert(result.Count == 1);
Debug.Assert(result[0].CustomerId == 1);
The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).
import numpy as np
import matplotlib.pyplot as plt
N = 3
ind = np.arange(N) # the x locations for the groups
width = 0.27 # the width of the bars
fig = plt.figure()
ax = fig.add_subplot(111)
yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')
ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )
def autolabel(rects):
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
plt.show()
This seems like a hack but if you use raw values you can do something like this
enum Suit: Int {
case Spades = 0, Hearts, Diamonds, Clubs
...
}
var suitIndex = 0
while var suit = Suit.fromRaw(suitIndex++) {
...
}
You need to use
$rootScope.$broadcast()
in the controller that must send datas. And in the one that receive those datas, you use
$scope.$on
Here is a fiddle that i forked a few time ago (I don't know who did it first anymore
You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.
Year(Date)
Year()
: Returns the year portion of the date argument.
Date
: Current date only.
Explanation of both of these functions from here.
Use:
<!-- This is a comment for an HTML page and it will not display in the browser -->
For more information, I think 3 On SGML and HTML may help you.
I often find convenient, inside my scripts, to define an iterable
function.
(Now incorporates Alfe's suggested simplification):
import collections
def iterable(obj):
return isinstance(obj, collections.Iterable):
so you can test if any object is iterable in the very readable form
if iterable(obj):
# act on iterable
else:
# not iterable
as you would do with thecallable
function
EDIT: if you have numpy installed, you can simply do: from numpy import iterable
,
which is simply something like
def iterable(obj):
try: iter(obj)
except: return False
return True
If you do not have numpy, you can simply implement this code, or the one above.
When you create the emulator, you need to choose properties CPU/ABI is Intel Atom (installed it in SDK manager )
Returns last day of last month:
>>> import datetime
>>> datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
datetime.datetime(2020, 9, 30, 14, 13, 15, 67582)
Returns the same day last month:
>>> x = datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
>>> x.replace(day=datetime.datetime.now().day)
datetime.datetime(2020, 9, 7, 14, 22, 14, 362421)
When an activity is created it's onCreate() method is called.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
savedInstanceState is an object of Bundle class which is null for the first time, but it contains values when it is recreated. To save Activity's state you have to override onSaveInstanceState().
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key","Welcome Back")
super.onSaveInstanceState(outState); //save state
}
put your values in "outState" Bundle object like outState.putString("key","Welcome Back") and save by calling super. When activity will be destroyed it's state get saved in Bundle object and can be restored after recreation in onCreate() or onRestoreInstanceState(). Bundle received in onCreate() and onRestoreInstanceState() are same.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore activity's state
if(savedInstanceState!=null){
String reStoredString=savedInstanceState.getString("key");
}
}
or
//restores activity's saved state
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
String restoredMessage=savedInstanceState.getString("key");
}
Different solution, webkit based. As mentioned already, anytime Chrome finds a password field it autocompletes the email. AFAIK, this is regardless of autocomplete = [whatever].
To circumvent this change the input type to text and apply the webkit security font in whatever form you want.
.secure-font{
-webkit-text-security:disc;}
<input type ="text" class="secure-font">
From what I can see this is at least as secure as input type=password, it's copy and paste secure. However it is vulnerable by removing the style which will remove asterisks, of course input type = password can easily be changed to input type = text in the console to reveal any autofilled passwords so it's much the same really.
The IFRAME
element may be a security risk if your site is embedded inside an IFRAME
on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe>
or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY
and hope that the browser knows its job.
In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe>
on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY
and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).
That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.
If somebody claims that using an <iframe>
element on your site is dangerous and causes a security risk, he does not understand what <iframe>
element does, or he is speaking about possibility of <iframe>
related vulnerabilities in browsers. Security of <iframe src="...">
tag is equal to <img src="..."
or <a href="...">
as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>
, <img>
or <a>
element, so it's not worth considering for this issue.
However, be warned that content from <iframe>
can initiate top level navigation by default. That is, content within the <iframe>
is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox
attribute without value allow-top-navigation
. For example, <iframe sandbox="allow-forms allow-scripts" ...>
. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.
Note that X-Frame-Options: DENY
also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").
It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.
You can do with some step bellow
Step 1: press Ctr + A(windows) or cmd + A (Mac os)
Step 2: Ctr + I in windows or cmd + I in Mac os
It will auto format for you
Regards
You're looking for a response header of Set-Cookie
:
xhr.getResponseHeader('Set-Cookie');
It won't work with HTTPOnly cookies though.
According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader()
, so the only reason why this could work is basically a "naughty" browser.
This question already has a lot of answers, but Mathias Bynens mentioned that 'utf8mb4' should be used instead of 'utf8' in order to have better UTF-8 support ('utf8' does not support 4 byte characters, fields are truncated on insert). I consider this to be an important difference. So here is yet another answer on how to set the default character set and collation. One that'll allow you to insert a pile of poo ().
This works on MySQL 5.5.35.
Note, that some of the settings may be optional. As I'm not entirely sure that I haven't forgotten anything, I'll make this answer a community wiki.
mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | utf8_general_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)
#
# UTF-8 should be used instead of Latin1. Obviously.
# NOTE "utf8" in MySQL is NOT full UTF-8: http://mathiasbynens.be/notes/mysql-utf8mb4
[client]
default-character-set = utf8mb4
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
[mysql]
default-character-set = utf8mb4
mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
+----------------------+--------------------+
| Variable_name | Value |
+----------------------+--------------------+
| collation_connection | utf8mb4_general_ci |
| collation_database | utf8mb4_unicode_ci |
| collation_server | utf8mb4_unicode_ci |
+----------------------+--------------------+
3 rows in set (0.00 sec)
character_set_system is always utf8.
This won't affect existing tables, it's just the default setting (used for new tables). The following ALTER code can be used to convert an existing table (without the dump-restore workaround):
ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Edit:
On a MySQL 5.0 server: character_set_client, character_set_connection, character_set_results, collation_connection remain at latin1. Issuing SET NAMES utf8
(utf8mb4 not available in that version) sets those to utf8 as well.
Caveat:
If you had a utf8 table with an index column of type VARCHAR(255), it can't be converted in some cases, because the maximum key length is exceeded (Specified key was too long; max key length is 767 bytes.
). If possible, reduce the column size from 255 to 191 (because 191 * 4 = 764 < 767 < 192 * 4 = 768). After that, the table can be converted.
If you want to print in the tabular form with, then you can use this:
echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;
Bitcode (iOS, watchOS)
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Basically this concept is somewhat similar to java where byte code is run on different JVM's and in this case the bitcode is placed on iTune store and instead of giving the intermediate code to different platforms(devices) it provides the compiled code which don't need any virtual machine to run.
Thus we need to create the bitcode once and it will be available for existing or coming devices. It's the Apple's headache to compile an make it compatible with each platform they have.
Devs don't have to make changes and submit the app again to support new platforms.
Let's take the example of iPhone 5s when apple introduced x64
chip in it. Although x86
apps were totally compatible with x64
architecture but to fully utilise the x64
platform the developer has to change the architecture or some code. Once s/he's done the app is submitted to the app store for the review.
If this bitcode concept was launched earlier then we the developers doesn't have to make any changes to support the x64
bit architecture.
The maven dependency plugin can potentially solve your problem.
If you have a pom
with all your project dependencies specified, all you would need to do is run
mvn dependency:copy-dependencies
and you will find the target/dependencies
folder filled with all the dependencies, including transitive.
Adding Gustavo's answer from below: To download the dependency sources, you can use
mvn dependency:copy-dependencies -Dclassifier=sources
Changing your lists to numpy
arrays will do the job!!
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15
plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()
If you only need to execute a single command, script block, or script file in .NET 4, try using Activation Configuration Files from .NET 4 to start only a single instance of PowerShell using version 4 of the CLR.
Full details:
http://blog.codeassassin.com/2011/03/23/executing-individual-powershell-commands-using-net-4/
An example PowerShell module:
I started mongod in cmd,It threw error like C:\data\db\ not found. Created folder then typed mongod opened another cmd typed mongo it worked.
The EXCEL and OLED DB connection managers use the parameter names 0 and 1.
I was using a oledb connection and wasted couple of hours trying to figure out the reason why the query was not working or taking the parameters. the above explanation helped a lot Thanks a lot.
Ran into this exact problem.
What I ended up doing:
# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'
# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)
# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
# set timezone
import pendulum
tz = pendulum.timezone('utc')
dt_tz = datetime(*dt_vals,tzinfo=tz)
Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time
#!/bin/bash
path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)
filename=log_$timestamp.txt
log=$path$filename
days=7
START_TIME=$(date +%s)
find $path -maxdepth 1 -name "*.txt" -type f -mtime +$days -print -delete >> $log
echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log
... code for backup ...or any other operation .... >> $log
END_TIME=$(date +%s)
ELAPSED_TIME=$(( $END_TIME - $START_TIME ))
echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time :: $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) " >> $log
The code adds a few things.
Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.
Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'
Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days
-mtime +$days ---> -mmin +$((60*24*$days))
You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.
If you've got a Mac the easiest way to split those would be to use DfontSplitter, available at https://peter.upfold.org.uk/projects/dfontsplitter
The Windows version they provide doesn't work with ttc files.
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList
for example uses a backing Array
. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
Right click the Maven Project -> Build Path -> Configure Build Path Go to Order and Export tab, you can see the message like '2 build path entries are missing' Now select 'JRE System Library' and 'Maven Dependencies' checkbox Click OK
use:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
You can use JSON.stringify() method to convert JSON object to String.
var j={"name":"binchen"};
JSON.stringify(j)
For reverse process, you can use JSON.parse() method to convert JSON String to JSON Object.
In addition to other people's answers of readability, maintainability, shorter code and therefore fewer bugs, and being much easier, I'll add an additional reason:
program speed.
Yes, in assembly you can hand tune your code to make use of every last cycle and make it as fast as is physically possible. However who has the time? If you write a not-completely-stupid C program, the compiler will do a really good job of optimizing for you. Probably making at least 95% of the optimizations you'd do by hand, without you having to worry about keeping track of any of it. There's definitely a 90/10 kind of rule here, where that last 5% of optimizations will end up taking up 95% of your time. So why bother?
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Update 2 (28 September 2020): This language is constantly evolving, and so if you can use Partial
(introduced in v2.1) then this is now my preferred way to achieve this.
class Box {
x: number;
y: number;
height: number;
width: number;
public constructor(b: Partial<Box> = {}) {
Object.assign(this, b);
}
}
// Example use
const a = new Box();
const b = new Box({x: 10, height: 99});
const c = new Box({foo: 10}); // Will fail to compile
Update (8 June 2017): guyarad and snolflake make valid points in their comments below to my answer. I would recommend readers look at the answers by Benson, Joe and snolflake who have better answers than mine.*
Original Answer (27 January 2014)
Another example of how to achieve constructor overloading:
class DateHour {
private date: Date;
private relativeHour: number;
constructor(year: number, month: number, day: number, relativeHour: number);
constructor(date: Date, relativeHour: number);
constructor(dateOrYear: any, monthOrRelativeHour: number, day?: number, relativeHour?: number) {
if (typeof dateOrYear === "number") {
this.date = new Date(dateOrYear, monthOrRelativeHour, day);
this.relativeHour = relativeHour;
} else {
var date = <Date> dateOrYear;
this.date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
this.relativeHour = monthOrRelativeHour;
}
}
}
Source: http://mimosite.com/blog/post/2013/04/08/Overloading-in-TypeScript
Using dateadd to remove a week from the current date.
datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()
You want getActivity()
inside your class. It's better to use
yourclassname.this.getActivity()
Try this. It's helpful for you.
use the following inside the body tag
<body onclick="theFunction(event)">
then use in javascript the following function to get the ID
<script>
function theFunction(e)
{ alert(e.target.id);}
I had the same problem, so here's what I came up with. This is what my folder structure looked like when I ran node server.js
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use(express.static(__dirname + '/default.htm'));
should actually be
app.use(express.static(__dirname));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Overall, your code could look like:
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.listen(process.env.PORT);
I needed to exclude names that started with an underscore from a query, so I ended up with this:
WHERE b.[name] not like '\_%' escape '\' -- use \ as the escape character
Instead of creating a new virtual environment, you just have to access to your initially created virtual environment when you started the project.
You just have to do the following in your command line:
1)pipenv shell
to access the backend virtual environment that you have initially created.
2) Then, python manage.py runserver
Let me know if it works for you or not.
There might be a situation when you want to use NodeJS environment variable to specify Angular CLI dev server port. One of the possible solution is to move CLI dev server running into a separate NodeJS script, which will read port value (e.g from .env file) and use it executing ng serve
with port
parameter:
// run-env.js
const dotenv = require('dotenv');
const child_process = require('child_process');
const config = dotenv.config()
const DEV_SERVER_PORT = process.env.DEV_SERVER_PORT || 4200;
const child = child_process.exec(`ng serve --port=${DEV_SERVER_PORT}`);
child.stdout.on('data', data => console.log(data.toString()));
Then you may a) run this script directly via node run-env
, b) run it via npm by updating package.json, for example
"scripts": {
"start": "node run-env"
}
run-env.js
should be committed to the repo, .env
should not. More details on the approach can be found in this post: How to change Angular CLI Development Server Port via .env.
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
For a somewhat more concise solution, consider the following:
def split_path(p):
a,b = os.path.split(p)
return (split_path(a) if len(a) and len(b) else []) + [b]
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),
The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max
key (as opposed to the dict
key) you can easily extract the highest value and its associated key.
mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)
One way to fix up your python2 code is:
import sys
if sys.version_info >= (3, 0):
def xrange(*args, **kwargs):
return iter(range(*args, **kwargs))
If you decide to use Underscore.js you better do
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
keys.push(key);
});
console.log(keys);
<input type="text" />
<script>
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
</script>
use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.
Just adding another solution that works for me.. You can simply append it in the marker options:
var marker = new google.maps.Marker({
map: map,
position: position,
// Custom Attributes / Data / Key-Values
store_id: id,
store_address: address,
store_type: type
});
And then retrieve them with:
marker.get('store_id');
marker.get('store_address');
marker.get('store_type');
I think you're mixing up two different paradigms here.
As you noted, the highly flexible ExternalProject
module runs its commands at build time, so you can't make direct use of Project A's import file since it's only created once Project A has been installed.
If you want to include
Project A's import file, you'll have to install Project A manually before invoking Project B's CMakeLists.txt - just like any other third-party dependency added this way or via find_file
/ find_library
/ find_package
.
If you want to make use of ExternalProject_Add
, you'll need to add something like the following to your CMakeLists.txt:
ExternalProject_Add(project_a
URL ...project_a.tar.gz
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/project_a
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
)
include(${CMAKE_CURRENT_BINARY_DIR}/lib/project_a/project_a-targets.cmake)
ExternalProject_Get_Property(project_a install_dir)
include_directories(${install_dir}/include)
add_dependencies(project_b_exe project_a)
target_link_libraries(project_b_exe ${install_dir}/lib/alib.lib)
From Python 3.6 onwards, the standard dict
type maintains insertion order by default.
Defining
d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}
will result in a dictionary with the keys in the order listed in the source code.
This was achieved by using a simple array with integers for the sparse hash table, where those integers index into another array that stores the key-value pairs (plus the calculated hash). That latter array just happens to store the items in insertion order, and the whole combination actually uses less memory than the implementation used in Python 3.5 and before. See the original idea post by Raymond Hettinger for details.
In 3.6 this was still considered an implementation detail; see the What's New in Python 3.6 documentation:
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).
Python 3.7 elevates this implementation detail to a language specification, so it is now mandatory that dict
preserves order in all Python implementations compatible with that version or newer. See the pronouncement by the BDFL. As of Python 3.8, dictionaries also support iteration in reverse.
You may still want to use the collections.OrderedDict()
class in certain cases, as it offers some additional functionality on top of the standard dict
type. Such as as being reversible (this extends to the view objects), and supporting reordering (via the move_to_end()
method).
You can't with inline styling alone. Do not recommend reimplementing CSS features in JavaScript we already have a language that is extremely powerful and incredibly fast built for this use case -- CSS. So use it! Made Style It to assist.
npm install style-it --save
Functional Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return Style.it(`
.intro:hover {
color: red;
}
`,
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
);
}
}
export default Intro;
JSX Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.intro:hover {
color: red;
}
`}
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
</Style>
}
}
export default Intro;
if you use Bootstrap 2.2.1 then maybe is this what you are looking for.
Sample file index.html
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
<link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
<menu>_x000D_
<div class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="/">Application name</a>_x000D_
</div>_x000D_
<div class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="/">Home</a></li>_x000D_
<li><a href="/Home/About">About</a></li>_x000D_
<li><a href="/Home/Contact">Contact</a></li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
<li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
</ul>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</menu>_x000D_
_x000D_
<nav>_x000D_
<div class="col-md-2">_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
</div>_x000D_
_x000D_
</nav>_x000D_
<content>_x000D_
<div class="col-md-10">_x000D_
_x000D_
<h2>About.</h2>_x000D_
<h3>Your application description page.</h3>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<hr />_x000D_
</div>_x000D_
</content>_x000D_
_x000D_
<footer>_x000D_
<div class="navbar navbar-default navbar-fixed-bottom">_x000D_
<div class="container" style="font-size: .8em">_x000D_
<p class="navbar-text">_x000D_
© Some info_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
body {_x000D_
padding-bottom: 70px;_x000D_
padding-top: 70px;_x000D_
}
_x000D_
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.
BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.
I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.
The answer from skaffman is definitely the correct answer. All logger methods such as error()
, warn()
, info()
, debug()
take Throwable as a second parameter:
try {
...
} catch (Exception e) {
logger.error("error: ", e);
}
However, you can extract stacktrace as a String as well. Sometimes it could be useful if you wish to take advantage of formatting feature using "{}" placeholder - see method void info(String var1, Object... var2);
In this case say you have a stacktrace as String, then you can actually do something like this:
try {
...
} catch (Exception e) {
String stacktrace = TextUtils.getStacktrace(e);
logger.error("error occurred for usename {} and group {}, details: {}",username, group, stacktrace);
}
This will print parametrized message and the stacktrace at the end the same way it does for method: logger.error("error: ", e);
I actually wrote an open source library that has a Utility for extraction of a stacktrace as a String with an option to smartly filter out some noise out of stacktrace. I.e. if you specify the package prefix that you are interested in your extracted stacktrace would be filtered out of some irrelevant parts and leave you with very consized info. Here is the link to the article that explains what utilities the library has and where to get it (both as maven artifacts and git sources) and how to use it as well. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison See the paragraph "Stacktrace noise filter"
Here's a quick two-liner that I use to quickly create a file if it doesn't exists.
if not os.path.exists(filename):
open(filename, 'w').close()
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:
Using this will save you extra coding on cross platform developments.
IE.
$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);
If you looped through this twice you would see in 'somefile':
some data
some data
Below script will store the ip address to the variable ip_address
@echo off
call :get_ip_address
echo %ip_address%
goto :eof
REM
REM get the ip address
REM
:get_ip_address
FOR /f "tokens=1 delims=:" %%d IN ('ping %computername% -4 -n 1 ^| find /i "reply"') do (FOR /F "tokens=3 delims= " %%g IN ("%%d") DO set ip_address=%%g)
goto :eof
Ideas from this blog post.
To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.
Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving
[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.
Goto Setting->Plugin->Search for "Lombok Plugin" -> It will show results. Install Lombok Plugin from the list and Restart Intellij
Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.
Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/
It gives a great example on how to open a new window*.
If you wish to use raw javascript then this is what you're looking for:
window.open(URL,name,specs,replace)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for RegexUtilities
/// </summary>
public class RegexUtilities
{
bool InValid = false;
public bool IsValidEmail(string strIn)
{
InValid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
if (InValid)
return false;
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
InValid = true;
}
return match.Groups[1].Value + domainName;
}
}
private void GetSendEmInfo()
{
#region For Get All Type Email Informations..!!
IPL.DoId = ddlName.SelectedValue;
DataTable dt = IdBL.GetEmailS(IPL);
if (dt.Rows.Count > 0)
{
hid_MailId.Value = dt.Rows[0]["MailId"].ToString();
hid_UsedPName.Value = dt.Rows[0]["UName"].ToString();
hid_EmailSubject.Value = dt.Rows[0]["EmailSubject"].ToString();
hid_EmailBody.Value = dt.Rows[0]["EmailBody"].ToString();
hid_EmailIdName.Value = dt.Rows[0]["EmailIdName"].ToString();
hid_EmPass.Value = dt.Rows[0]["EPass"].ToString();
hid_SeName.Value = dt.Rows[0]["SenName"].ToString();
hid_TNo.Value = dt.Rows[0]["TeNo"].ToString();
hid_EmaLimit.Value = dt.Rows[0]["EmailLimit"].ToString();
hidlink.Value = dt.Rows[0][link"].ToString();
}
#endregion
#region For Set Some Local Variables..!!
int StartLmt, FinalLmt, SendCurrentMail;
StartLmt = FinalLmt = SendCurrentMail = 0;
bool Valid_LimitMail;
Valid_LimitMail = true;
/**For Get Finalize Limit For Send Mail**/
FinalLmt = Convert.ToInt32(hid_EmailmaxLimit.Value);
#region For Check Email Valid Limits..!!
if (FinalLmt > 0)
{
Valid_LimitMail = true;
}
else
{
Valid_LimitMail = false;
}
#endregion
/**For Get Finalize Limit For Send Mail**/
#endregion
if (Valid_LimitMail == true)
{
#region For Send Current Email Status..!!
bool EmaiValid;
string CreateFileName;
string retmailflg = null;
EmaiValid = false;
#endregion
#region For Set Start Limit And FinalLimit Send No Of Email..!!
mPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
DataTable dtsendEmail = m1BL.GetEmailSendLog(mPL);
if (dtsendEmail.Rows.Count > 0)
{
StartLmt = Convert.ToInt32(dtsendEmail.Rows[0]["SendNo_Of_Email"].ToString());
}
else
{
StartLmt = 0;
}
#endregion
#region For Find Grid View Controls..!!
for (int i = 0; i < GrdEm.Rows.Count; i++)
{
#region For Find Grid view Controls..!!
CheckBox Chk_SelectOne = (CheckBox)GrdEmp.Rows[i].FindControl("chkSingle");
Label lbl_No = (Label)GrdEmAtt.Rows[i].FindControl("lblGrdCode");
lblCode.Value = lbl_InNo.Text;
Label lbl_EmailId = (Label)GrdEomAtt.Rows[i].FindControl("lblGrdEmpEmail");
#endregion
/**Region For If Check Box Checked Then**/
if (Chk_SelectOne.Checked == true)
{
if (!string.IsNullOrEmpty(lbl_EmailId.Text))
{
#region For When Check Box Checked..!!
/**If Start Limit Less Or Equal To Then Condition Performs**/
if (StartLmt < FinalLmt)
{
StartLmt = StartLmt + 1;
}
else
{
Valid_LimitMail = false;
EmaiValid = false;
}
/**End Region**/
string[] SplitClients_Email = lbl_EmailId.Text.Split(',');
string Send_Email, Hold_Email;
Send_Email = Hold_Email = "";
int CountEmail;/**Region For Count Total Email**/
CountEmail = 0;/**First Time Email Counts Zero**/
Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
/**Region For If Clients Have One Email**/
#region For First Emails Send On Client..!!
if (SplitClients_Email[0].ToString() != "")
{
if (EmailRegex.IsValidEmail(Hold_Email))
{
Send_Email = Hold_Email;
CountEmail = 1;
EmaiValid = true;
}
else
{
EmaiValid = false;
}
}
#endregion
/**Region For If Clients Have One Email**/
/**Region For If Clients Have Two Email**/
/**Region For If Clients Have Two Email**/
if (EmaiValid == true)
{
#region For Create Email Body And Create File Name..!!
//fofile = Server.MapPath("PDFs");
fofile = Server.MapPath("~/vvv/vvvv/") + "/";
CreateFileName = lbl_INo.Text.ToString() + "_1" + ".Pdf";/**Create File Name**/
string[] orimail = Send_Email.Split(',');
string Billbody, TempInvoiceId;
// DateTime dtLstdate = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 16);
// DateTime IndtLmt = dtLstdate.AddMonths(1);
TempInvoiceId = "";
//byte[] Buffer = Encrypt.Encryptiondata(lbl_InvoiceNo.Text.ToString());
//TempInvoiceId = Convert.ToBase64String(Buffer);
#region Create Encrypted Path
byte[] EncCode = Encrypt.Encryptiondata(lbl_INo.Text);
hidEncrypteCode.Value = Convert.ToBase64String(EncECode);
#endregion
//#region Create Email Body !!
//body = hid_EmailBody.Value.Replace("@greeting", lbl_CoName.Text).Replace("@free", hid_ToNo.Value).Replace("@llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://1ccccc/ccc/ccc/ccc.aspx?EC=" + hidEncryptedCode.Value+ "' > C cccccccc </a>");
body = hid_EmailBody.Value.Replace("@greeting", "Hii").Replace("@No", hid_No.Value);/*For Mail*/
//#endregion
#region For Email Sender Informations..!!
for (int j = 0; j < CountEmail; j++)
{
//if (File.Exists(fofile + "\\" + CreateFileName))
//{
#region
lbl_EmailId.Text = orimail[j];
retmailflg = "";
/**Region For Send Email For Clients**/
//retmailflg = SendPreMail("Wp From " + lbl_CName.Text + "", body, lbl_EmailId.Text, lbl_IeNo.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
retmailflg = SendPreMail(hid_EmailSubject.Value, Body, lbl_EmailId.Text, lbl_No.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
/**End Region**/
/**Region For Create Send Email Log When Email Send Successfully**/
if (retmailflg == "True")
{
SendCurrentMail = Convert.ToInt32(SendCurrentMail) + 1;
StartLmt = Convert.ToInt32(StartLmt) + 1;
if (SendCurrentMail > 0)
{
CreateEmailLog(lbl_InNo.Text, StartLmt, hid_EmailIdName.Value, lbl_EmailId.Text);
}
}
/**End Region**/
#endregion
//}
}
#endregion
}
#endregion
}
}
/**End Region**/
}
#endregion
}
}
private void CreateEmailLog(string UniqueId, int StartLmt, string FromEmailId, string TotxtEmailId)
{
FPL.EmailId_From = FromEmailId;
FPL.To_EmailId = TotxtEmailId;
FPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
FPL.EmailUniqueId = UniqueId;
FPL.SendNo_Of_Email = StartLmt.ToString();
FPL.LoginUserId = Session["LoginUserId"].ToString();
int i = FBL.InsertEmaDoc(FPL);
}
public string SendPreMail(string emsub, string embody, string EmailId, string FileId, string EmailFromId, string Password)
{
string retval = "False";
try
{
string emailBody, emailSubject, emailToList, emailFrom,
accountPassword, smtpServer;
bool enableSSL;
int port;
emailBody = embody;
emailSubject = emsub;
emailToList = EmailId;
emailFrom = EmailFromId;
accountPassword = Password;
smtpServer = "smtp.gmail.com";
enableSSL = true;
port = 587;
string crefilename;
string fofile;
fofile = Server.MapPath("PDF");
crefilename = FileId + ".Pdf";
string[] att = { crefilename };
string retemail, insertqry;
retemail = "";
retemail = SendEmail(emailBody, emailSubject, emailFrom, emailToList, att, smtpServer, enableSSL, accountPassword, port);
if (retemail == "True")
{
retval = retemail;
}
}
catch
{
retval = "False";
}
finally
{
}
return retval;
}
public string SendEmail(string emailBody, string emailSubject, string emailFrom, string emailToList, string[] attachedFiles, string smtpIPAddress, bool enableSSL, string accountPassword, int port)
{
MailMessage mail = new MailMessage();
string retflg;
retflg = "False";
try
{
mail.From = new MailAddress(emailFrom);
if (emailToList.Contains(";"))
{
emailToList = emailToList.Replace(";", ",");
}
mail.To.Add(emailToList);
mail.Subject = emailSubject;
mail.IsBodyHtml = true;
mail.Body = emailBody;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(emailFrom, accountPassword);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mail);
retflg = "True";
}
catch
{
retflg = "False";
}
finally
{
mail.Dispose();
}
return retflg;
}
This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
Your if statements are checking for int values. raw_input
returns a string. Change the following line:
tSizeAns = raw_input()
to
tSizeAns = int(raw_input())
var icon1 = "imageA.png";
var icon2 = "imageB.png";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon1,
title: "some marker"
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
});
Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.
The ?
as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.
Let's compare these two patterns: A.*Z
and A.*?Z
.
Given the following input:
eeeAiiZuuuuAoooZeeee
The patterns yield the following matches:
A.*Z
yields 1 match: AiiZuuuuAoooZ
(see on rubular.com)A.*?Z
yields 2 matches: AiiZ
and AoooZ
(see on rubular.com)Let's first focus on what A.*Z
does. When it matched the first A
, the .*
, being greedy, first tries to match as many .
as possible.
eeeAiiZuuuuAoooZeeee
\_______________/
A.* matched, Z can't match
Since the Z
doesn't match, the engine backtracks, and .*
must then match one fewer .
:
eeeAiiZuuuuAoooZeeee
\______________/
A.* matched, Z still can't match
This happens a few more times, until finally we come to this:
eeeAiiZuuuuAoooZeeee
\__________/
A.* matched, Z can now match
Now Z
can match, so the overall pattern matches:
eeeAiiZuuuuAoooZeeee
\___________/
A.*Z matched
By contrast, the reluctant repetition in A.*?Z
first matches as few .
as possible, and then taking more .
as necessary. This explains why it finds two matches in the input.
Here's a visual representation of what the two patterns matched:
eeeAiiZuuuuAoooZeeee
\__/r \___/r r = reluctant
\____g____/ g = greedy
In many applications, the two matches in the above input is what is desired, thus a reluctant .*?
is used instead of the greedy .*
to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.
The pattern A[^Z]*Z
also finds the same two matches as the A.*?Z
pattern for the above input (as seen on ideone.com). [^Z]
is what is called a negated character class: it matches anything but Z
.
The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.
This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.
eeAiiZooAuuZZeeeZZfff
These are the matches for the above input:
A[^Z]*ZZ
yields 1 match: AuuZZ
(as seen on ideone.com)A.*?ZZ
yields 1 match: AiiZooAuuZZ
(as seen on ideone.com)A.*ZZ
yields 1 match: AiiZooAuuZZeeeZZ
(as seen on ideone.com)Here's a visual representation of what they matched:
___n
/ \ n = negated character class
eeAiiZooAuuZZeeeZZfff r = reluctant
\_________/r / g = greedy
\____________/g
These are links to questions and answers on stackoverflow that cover some topics that may be of interest.
There are a couple of things that need to be adjusted in your layout:
You are nesting col
elements within form-group
elements. This should be the other way around (the form-group
should be within the col-sm-xx
element).
You should always use a row
div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12
is still on the same row with the above 3 .col-sm-4
resulting in a total of columns greater than 12, and causing the overlap problem.
Here is a fixed demo.
And an excerpt of what the problematic section HTML should become:
<fieldset>
<legend>Personal Information</legend>
<div class='row'>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_title">Title</label>
<input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_firstname">First name</label>
<input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_lastname">Last name</label>
<input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-12'>
<div class='form-group'>
<label for="user_email">Email</label>
<input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
</div>
</div>
</div>
</fieldset>
I have also experienced this scenario.
I have a bucket with policy that uses AWS4-HMAC-SHA256. Turns out my awscli is not updated to the latest version. Mine was aws-cli/1.10.8. Upgrading it have solved the problem.
pip install awscli --upgrade --user
https://docs.aws.amazon.com/cli/latest/userguide/installing.html
Via SQL as per MSDN
SET IDENTITY_INSERT sometableWithIdentity ON
INSERT INTO sometableWithIdentity
(IdentityColumn, col2, col3, ...)
VALUES
(AnIdentityValue, col2value, col3value, ...)
SET IDENTITY_INSERT sometableWithIdentity OFF
The complete error message tells you exactly what is wrong...
Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.
A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete.
you refer to my blog:enter link description here
You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.
if [ "$1" == "something" ]; then ## GOOD
if [ "$1" = "something" ]; then ## GOOD
if [ "$1"="something" ]; then ## BAD (operator spacing)
if ["$1" == "something"]; then ## BAD (bracket spacing)
Also, note double brackets are handled slightly differently compared to single brackets ...
if [[ $a == z* ]]; then # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).
if [ $a == z* ]; then # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).
I hope that helps!
@bninopaul 's answer is not completely for beginners
here is the code you can "copy and run"
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[13,1,1,0,2,0],
[3,9,6,0,1,0],
[0,0,16,2,0,0],
[0,0,0,13,0,0],
[0,0,0,0,15,0],
[0,0,1,0,0,15]]
df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size
plt.show()
Just in case someone is using Bootstrap 4. It seems we can no longer use .modal-backdrop.in
, but must now use .modal-backdrop.show
. Fade effect preserved.
.modal-backdrop.show {
opacity: 0.7;
}
A SOAP document is sent per request. Say we were a book store, and had a remote server we queried to learn the current price of a particular book. Say we needed to pass the Book's title, number of pages and ISBN number to the server.
Whenever we wanted to know the price, we'd send a unique SOAP message. It'd look something like this;
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:GetBookPrice xmlns:m="http://namespaces.my-example-book-info.com">
<ISBN>978-0451524935</ISBN>
<Title>1984</Title>
<NumPages>328</NumPages>
</m:GetBookPrice>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
And we expect to get a SOAP response message back like;
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:GetBookPriceResponse xmlns:m="http://namespaces.my-example-book-info.com">
<CurrentPrice>8.99</CurrentPrice>
<Currency>USD</Currency>
</m:GetBookPriceResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The WSDL then describes how to handle/process this message when a server receives it. In our case, it describes what types the Title, NumPages & ISBN would be, whether we should expect a response from the GetBookPrice message and what that response should look like.
The types would look like this;
<wsdl:types>
<!-- all type declarations are in a chunk of xsd -->
<xsd:schema targetNamespace="http://namespaces.my-example-book-info.com"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<xsd:element name="GetBookPrice">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ISBN" type="string"/>
<xsd:element name="Title" type="string"/>
<xsd:element name="NumPages" type="integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="GetBookPriceResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="CurrentPrice" type="decimal" />
<xsd:element name="Currency" type="string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</wsdl:types>
But the WSDL also contains more information, about which functions link together to make operations, and what operations are avaliable in the service, and whereabouts on a network you can access the service/operations.
See also W3 Annotated WSDL Examples
First Strong/Weak Reference types are introduced in ARC. In Non ARC assign/retain are being used. A strong reference means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you points to it with a strong reference. Only once you set the property to nil, the object get destroyed.
A weak reference means you signify that you don't want to have control over the object's lifetime or don't want to "own" object. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are for IBOutlets, Delegates etc.
For more info Refer : http://www.informit.com/articles/article.aspx?p=1856389&seqNum=5
While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.
Example:
@echo off
SetLocal
set Lhs="
set Rhs="
if "%Lhs%" == "%Rhs%" echo Equal
Error:
echo was unexpected at this time.
Enable delayed expansion and use ! instead of %.
@echo off
SetLocal EnableDelayedExpansion
set Lhs="
set Rhs="
if !Lhs! == !Rhs! echo Equal
:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal
I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.
Test:
@echo off
SetLocal EnableDelayedExpansion
:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
For integers you can use Integer.signum()
Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)
Try this set of code to download a CSV file from the server.
byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
Could it be a one to many relationship between the left and right tables?
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.
Unset is a function. Therefore you have to submit which variable has to be destroyed.
unset($var);
In your case
unset ($_SESSION["products"]);
If you need to reset whole session variable just call
session_destroy ();
I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.
I usually lose track of all of my -20001
-type error codes, so I try to consolidate all my application errors into a nice package like such:
SET SERVEROUTPUT ON
CREATE OR REPLACE PACKAGE errors AS
invalid_foo_err EXCEPTION;
invalid_foo_num NUMBER := -20123;
invalid_foo_msg VARCHAR2(32767) := 'Invalid Foo!';
PRAGMA EXCEPTION_INIT(invalid_foo_err, -20123); -- can't use var >:O
illegal_bar_err EXCEPTION;
illegal_bar_num NUMBER := -20156;
illegal_bar_msg VARCHAR2(32767) := 'Illegal Bar!';
PRAGMA EXCEPTION_INIT(illegal_bar_err, -20156); -- can't use var >:O
PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL);
END;
/
CREATE OR REPLACE PACKAGE BODY errors AS
unknown_err EXCEPTION;
unknown_num NUMBER := -20001;
unknown_msg VARCHAR2(32767) := 'Unknown Error Specified!';
PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL) AS
v_msg VARCHAR2(32767);
BEGIN
IF p_err = unknown_num THEN
v_msg := unknown_msg;
ELSIF p_err = invalid_foo_num THEN
v_msg := invalid_foo_msg;
ELSIF p_err = illegal_bar_num THEN
v_msg := illegal_bar_msg;
ELSE
raise_err(unknown_num, 'USR' || p_err || ': ' || p_msg);
END IF;
IF p_msg IS NOT NULL THEN
v_msg := v_msg || ' - '||p_msg;
END IF;
RAISE_APPLICATION_ERROR(p_err, v_msg);
END;
END;
/
Then call errors.raise_err(errors.invalid_foo_num, 'optional extra text')
to use it, like such:
BEGIN
BEGIN
errors.raise_err(errors.invalid_foo_num, 'Insufficient Foo-age!');
EXCEPTION
WHEN errors.invalid_foo_err THEN
dbms_output.put_line(SQLERRM);
END;
BEGIN
errors.raise_err(errors.illegal_bar_num, 'Insufficient Bar-age!');
EXCEPTION
WHEN errors.illegal_bar_err THEN
dbms_output.put_line(SQLERRM);
END;
BEGIN
errors.raise_err(-10000, 'This Doesn''t Exist!!');
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLERRM);
END;
END;
/
produces this output:
ORA-20123: Invalid Foo! - Insufficient Foo-age!
ORA-20156: Illegal Bar! - Insufficient Bar-age!
ORA-20001: Unknown Error Specified! - USR-10000: This Doesn't Exist!!
You can simply use theatol()
function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *c = "5";
int d = atol(c);
printf("%d\n", d);
}
Same error Process with an ID #### is not running using visual studio 2015 RC.
Only go rid of the message after repair IIS 10 in Control Panel - Programs and Features
Renato
In your codethis
refers to the select element not to the selected option
to refer the selected option you can do this -
$(this).find('option:selected').attr("name");
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
console.log(str2 + " found");_x000D_
}
_x000D_
You can use the following CSS to make a div 100% of the height of the browser window:
display: block;
position: relative;
bottom: 0;
height: 100%;
I don't know if there's an easier way to do it without using an external library, but I personally love underscore.js which has tons of utilities for dealing with arrays, collections etc.
With underscore you could do this easily with one line of code:
_.pluck(arr, 'name').join(', ')
try this below solution:
exclude:path.resolve(__dirname, "node_modules")
Like this:
>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
I had the same problem when debugging over wlan. I could launch the application from Android Studio but couldn't get any messages in logcat.
I fixed it by connecting the device to my pc via USB cable, launched the application once and everything was working. Then I disconnected the USB cable and tried debugging again via wlan and everything was working again.
You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person
in this case. The default is to use std::less<T>
, which resolves to something equivalent to operator<
. This relies on it's own stored type having one. So if you were to implement
bool operator<(const Person& lhs, const Person& rhs);
it should work without any further changes. The implementation could be
bool operator<(const Person& lhs, const Person& rhs)
{
return lhs.age < rhs.age;
}
If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>
. For example,
struct LessThanByAge
{
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
then instantiate the queue like this:
std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
Concerning the use of std::greater<Person>
as comparator, this would use the equivalent of operator>
and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator>
that can operate on two Person
instances.
As the question is answered. For web develoment. I came so far and found a good explanation about bootsrapping in Laravel doc. Here is the link
In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes.
hope it will help someone who learning web application development.
Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
MongoClient.connect(url (err, client) => {
if(err) throw err;
let database = client.db('databaseName');
database.collection('name').find()
.toArray((err, results) => {
if(err) throw err;
results.forEach((value)=>{
console.log(value.name);
});
})
})
The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.
It's way late but you should look at this. Not CLI I know but still worth just knocking out a little shell script to do what you need:
https://pypi.org/project/aws-list-all/
It's a python library that in it's own words:
"Project description List all resources in an AWS account, all regions, all services(*). Writes JSON files for further processing.
(*) No guarantees for completeness. Use billing alerts if you are worried about costs."
If you're using Building Standalone Apps with Expo, the versionCode error might creep up owing to the fact that the standard app.json
config only has a reference to the version
property.
I was able to add a versionCode
property under android
as follows:
Sample App.json
{
"expo": {
"sdkVersion": "29.0.0",
"name": "App Name",
"version": "1.1.0",
"slug": "app-name",
"icon": "src/images/app-icon.png",
"privacy": "public",
"android": {
"package": "com.madhues.app",
"permissions": [],
"versionCode": 2 // Notice the versionCode added under android.
}
}
}
Detailed documentation: https://docs.expo.io/versions/v32.0.0/workflow/configuration/#versioncode
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
use getBoundingClientRect
if $el
is the actual DOM object:
var top = $el.getBoundingClientRect().top;
Fiddle will show that this will get the same value that jquery's offset top will give you
Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses
https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)
offset: function( options ) {
//...
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
}
If you just want to do it once, without adding a shortcut, you can always type
<prefix>
:
kill-window
<enter>
I like to use a global "app", rather than exporting a function etc
After researching a lot I feel most of the given answer will not work with dotnet core.
1.System.Diagnostics.Process.Start("http://google.com")
; -- Will not work with dotnet core
2.It will work but it will block the new window opening in case default browser is chrome
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
Below is the simplest and will work in all the scenarios.
Process.Start("explorer", url);
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Came across this issue in Xcode 11, fix was changing the Minimum Deployment Target from 10.0 to 11.0, hope this helps someone :)
It is surprisingly simple...
Code behind:
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
ASPX code:
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
I hope this helps!
In this case a[4]
is the 5th
integer in the array a
, ap
is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap
now holds 45
and when you try to de-reference it (by doing *ap
) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.
You should do ap = &(a[4]);
or ap = a + 4;
In c
array names decays to pointer, so a
points to the 1st element of the array.
In this way, a
is equivalent to &(a[0])
.
you can't increase the heap size dynamically.
you can request to use more by using android:largeHeap="true"
in the manifest.
also, you can use native memory (NDK & JNI)
, so you actually bypass the heap size limitation.
here are some posts i've made about it:
and here's a library i've made for it:
An <input>
's width is generated from its size
attribute. The default size
is what's driving the auto width.
You could try width:100%
as illustrated in my example below.
Doesn't fill width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:auto' />
</form>
Fills width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:100%' />
</form>
Smaller size, smaller width:
<form action='' method='post' style='width:200px;background:khaki'>
<input size='5' />
</form>
UPDATE
Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)
<div style='padding:30px;width:200px;background:red'>
<form action='' method='post' style='width:200px;background:blue;padding:3px'>
<input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
<br /><br />
<input size='' style='width:100%' />
</form>
</div>
For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be
docker.io/<dockerimagename>:version
The suggestion above of registry.hub.docker.com/library/<dockerimagename>
did not work for me.
I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)
<div id="foo">hello world!</div>
<img src="zoom.png" id="click_me" />
JS
$('#click_me').click(function(){
$('#foo').css({
'background-color':'red',
'color':'white',
'font-size':'44px'
});
});
When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:
<input type="radio" name="rdb" value="male"/>
then in your php code you need to use:
$rdb_value = $_POST['rdb'];
I was able to make this work by creating a named range in the current sheet that referred to the table I wanted to reference in the other sheet.
Default access modifier - If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).
As mentioned previously "there is no CSS selector for selecting a parent of a selected child".
So you either:
On the javascript side:
$('#my-id-selector-00').on('mouseover', function(){
$(this).parent().addClass('is-hover');
}).on('mouseout', function(){
$(this).parent().removeClass('is-hover');
})
And on the CSS side, you'd have something like this:
.is-hover {
background-color: red;
}
This is an old question but the number of responses tells me many people hit this page.
The easiest way I found is to just use the built in AWS console for creating an inventory. It's easy to set up but the first CSV file can take up to 48 hours to show up. After that you can create either a daily or weekly output to a bucket of your choosing.
The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.
I use this script to enable on a server, if the option is disabled:
if not exists(
SELECT value
FROM sys.configurations
WHERE name = 'clr enabled'
and value = 1
)
begin
exec sp_configure @configname=clr_enabled, @configvalue=1
reconfigure
end
string newString = str.Substring(0,10)
will give you the first 10 characters (from position 0 to position 9).
See here.
This could be unrelated to this specific problem, but I ran into a similar issue where I used NumPy indexing on a Python list and got the same exact error message:
# incorrect
weights = list(range(1, 129)) + list(range(128, 0, -1))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
# TypeError: only integer scalar arrays can be converted to a scalar index
It turns out I needed to turn weights
, a 1D Python list, into a NumPy array before I could apply multi-dimensional NumPy indexing. The code below works:
# correct
weights = np.array(list(range(1, 129)) + list(range(128, 0, -1)))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
I've just had this problem with MariaDB/InnoDB and was able to fix it by