As a variation on a theme, I could have sworn up and down that my Views\Web.config was correct:
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
But I in fact needed to reference Version=4.0.0.1
, not Version=4.0.0.0
because of that security update that got pushed out a while back.
You can focus on a split window using # ctrl-ww
.
for example, pressing:
1 ctrl-ww
would focus on the first window, usually being NERDTree.
Quote
Important: If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the
<button>
and</button>
tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.
From : http://www.w3schools.com/tags/tag_button.asp
If I understand correctly, the answer is compatibility and input consistency from browser to browser
As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.
using System.Management;
...
string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
foreach (PropertyData property in printer.Properties)
{
Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
}
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
My solution is:
import os
print(os.path.dirname(os.path.abspath(__file__)))
Example:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"build_c": "ng build --prod && del \"../../server/front-end/*.*\" /s /q & xcopy /s dist \"../../server/front-end\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
As you can see, the script "build_c" is building the angular application, then deletes all old files from a directory, then finally copies the result build files.
With Json.NET
public class Movie
{
public string Name { get; set; }
public string Description { get; set; }
public string Classification { get; set; }
public string Studio { get; set; }
public DateTime? ReleaseDate { get; set; }
public List<string> ReleaseCountries { get; set; }
}
Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";
string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
The result will be:
{
"Name": "Bad Boys III",
"Description": "It's no Bad Boys"
}
You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.
Node.js uses the environmental variable NODE_PATH
to allow for specifying additional directories to include in the module search path. You can use npm
itself to tell you where global modules are stored with the npm root -g
command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)
export NODE_PATH=$(npm root --quiet -g)
You mean you want 1b and 1b to be side by side?
<div class="col-lg-6 col-md-6 col-12 child1">
<div class="col-6 child1a">Child content 1a</div>
<div class="col-6 child1b">Child content 1b</div>
</div>
Decode it with the unicode-escape
codec:
>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…
This is because for a non-unicode string the \u2026
is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'
). You need to decode the escapes, and the unicode-escape
codec can do that for you.
Note that you can get unicode
to recognise it in the same way by specifying the codec argument:
>>> unicode(a, 'unicode-escape')
u'Hello\u2026'
But the a.decode()
way is nicer.
The other answers were incorrect, at least in my case. request.path
does not provide the full url, only the relative url, e.g. /paper/53
. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path
.
in standart Vi editor in this situation you should
I found the answer, thanks to your information Michelle.
You can indeed get the right view using View#getChildAt(int index)
. The catch is that it starts counting from the first visible item. In fact, you can only get the visible items. You solve this with ListView#getFirstVisiblePosition()
.
Example:
private void updateView(int index){
View v = yourListView.getChildAt(index -
yourListView.getFirstVisiblePosition());
if(v == null)
return;
TextView someText = (TextView) v.findViewById(R.id.sometextview);
someText.setText("Hi! I updated you manually!");
}
Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.
Ctrl + Enter - as simple as that!
This, for many people, will be better than autocompleting on everything.
You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:
-DAPP_MASTER_PASSWORD=foo
and in your code, write
System.getProperty("APP_MASTER_PASSWORD");
You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.
Ran into this similar issue while using iframe to logout of sub sites with different domains. The solution I used was to load the iframe first, then update the source after the frame is loaded.
var frame = document.createElement('iframe');_x000D_
frame.style.display = 'none';_x000D_
frame.setAttribute('src', 'about:blank');_x000D_
document.body.appendChild(frame);_x000D_
frame.addEventListener('load', () => {_x000D_
frame.setAttribute('src', url);_x000D_
});
_x000D_
This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.
Create an XML file Create XML file
Add the following code on the new XML file you created Add base-config
Add this on AndroidManifest.xml Add this code line
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
Another option would be to use the jQuery Transit Framework to handle your CSS3 transitions. The transitions/effects perform well on mobile devices and you don't have to add a single line of messy CSS3 transitions in your CSS file in order to do the animation effects.
Here is an example that will transition an element's opacity to 0 when you click on it and will be removed once the transition is complete:
$("#element").click( function () {
$('#element').transition({ opacity: 0 }, function () { $(this).remove(); });
});
Try:
document.location.protocol + '//' +
document.location.host +
document.location.pathname;
(NB: .host
rather than .hostname
so that the port gets included too, if necessary)
boolean isBeforeToday(Date d) {
Date today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return d.before(today);
}
To check whether a process/command returned 0 or not, use the operators && == 0 or
: not == 0 ||
Just add operator to your script:
execute_command && (
echo\Return 0, with no execution error
) || (
echo\Return non 0, something went wrong
)
command && echo\Return 0 || echo\Return non 0
I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.
On the Button:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
On the Server Event
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!
Its very very easy with Carbon.
$date = "2016-02-16"; // Or Your date
$newDate = Carbon::createFromFormat('Y-m-d', $date)->addYear(1);
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding the run() method with a version that does provide hooks.
Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!
From the JUnit javadoc:
delta - the maximum delta between expected and actual for which both numbers are still considered equal.
It's probably overkill, but I typically use a really small number, e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertEquals(123.456, 123.456, DELTA);
}
If you're using hamcrest assertions, you can just use the standard equalTo()
with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo()
(see javadoc), e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertThat(123.456, equalTo(123.456));
assertThat(123.456, closeTo(123.456, DELTA));
}
FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals()
with two doubles. The implementation (if you're interested) is:
private static boolean doublesAreEqual(double value1, double value2) {
return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}
I just open zshrc with sublime, and edit it.
subl .zshrc
And add this on sublime:
alias blah="/usr/bin/blah"
Run this in terminal:
source ~/.bashrc
Done.
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n with ","
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
If your text contains blank lines in between you can use regular expression \n+ instead of \n
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n+ with "," (in regex mode)
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
I had the same symptom. For me it turned out that another thread was modifying the compared objects while the sorting was happening in a Stream. To resolve the issue, I mapped the objects to immutable temporary objects, collected the Stream to a temporary Collection and did the sorting on that.
=Sumifs(B:B,A:A,">=1/1/2013",A:A,"<=1/31/2013")
The beauty of this formula is you can add more data to columns A and B and it will just recalculate.
i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.
Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like
.icon{
background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}
and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.
Good Luck!
Although this post seems to be old, I'd like to add the following two to inform about the recent development in this area for Android:
android-binding - Providing a framework that enabes the binding of android view widgets to data model. It helps to implement MVC or MVVM patterns in android applications.
roboguice - RoboGuice takes the guesswork out of development. Inject your View, Resource, System Service, or any other object, and let RoboGuice take care of the details.
You can use finds null separated output option with read to iterate over directory structures safely.
#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file;
do echo "$file" ;
done
So for your case
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done
additionally
#!/bin/bash
while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done < <(find . -maxdepth 1 -type f -print0)
will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed
Although there are so many answers to the question, I would like to share our experience of creating the endless list view. We have recently implemented custom Carousel LayoutManager that can work in the cycle by scrolling the list infinitely as well as up to a certain point. Here is a detailed description on GitHub.
I suggest you take a look at this article with short but valuable recommendations on creating custom LayoutManagers: http://cases.azoft.com/create-custom-layoutmanager-android/
you can append the jdbc url with
?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8
With the help of this, sql convert '0000-00-00 00:00:00' as null value.
eg:
jdbc:mysql:<host-name>/<db-name>?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8
You need to create the project on GitHub first. After that go to the project directory and run in terminal:
git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master
Exemple, for :
<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>
In this js code :
var myMarginTop = $("#myBlock").css("marginBottom");
The var becomes "15px", a string.
If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.
The fastest is to use native js method :
var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );
This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version
to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.
Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.
Seemed to be a no brainer; the WCF service should be enabled using Programs and Features -> Turn Windows features on or off
in the Control Panel. Go to .NET Framework Advanced Services -> WCF Services
and enable HTTP Activation
as described in this blog post on mdsn.
From the command prompt (as admin), you can run:
C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45
If you get an error then use the below
C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation45
just try
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
Note: To connect to server on SQL Server Management Studio(SSMS), we must first install SQL Server.
So steps to proceed are as
Step 1 : Downloads and Install Microsoft SQL Server 2019
Step 2 : Downloads and Install SQL Server Management Studio
If still not able to see the Server name on SSMS, have a look at these three screen:
Since the answers deviate I decided to test this and post the result - including the test example.
The server here just writes data to a client and does not expect any input.
The server:
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
out.println("output");
if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
System.out.println(clientSocket.isConnected());
System.out.println(clientSocket.getInputStream().read());
// thread sleep ...
// break condition , close sockets and the like ...
}
You need to extract the initilization of time() out of the for loop.
Here is an example that will output in the windows console expected (ahah) random number.
#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
srand ( time(NULL) );
for (int t = 0; t < 10; t++)
{
int random_x;
random_x = rand() % 100;
std::cout << "\nRandom X = " << random_x << std::endl;
}
Sleep(50000);
return 0;
}
The solution is not very efficient as pointed by Erwin, because of presence of SubQs
select * from purchases p1 where total in
(select max(total) from purchases where p1.customer=customer) order by total desc;
This is how i did it. I have a nav block that is below the header once you scroll the page down it 'sticks' to the top of the window. If you scroll back to top, nav goes back in it's place I use position:fixed in CSS for non mobile platforms and iOS5. Other Mobile versions do have that 'lag' until screen stops scrolling before it's set.
// css
#sticky.stick {
width:100%;
height:50px;
position: fixed;
top: 0;
z-index: 1;
}
// jquery
//sticky nav
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top)
$('#sticky').addClass('stick');
else
$('#sticky').removeClass('stick');
}
$(window).scroll(function(event){
// sticky nav css NON mobile way
sticky_relocate();
var st = $(this).scrollTop();
// sticky nav iPhone android mobile way iOS<5
if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i)) {
//do nothing uses sticky_relocate() css
} else if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ) {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').css({'top' : st , 'position' : 'absolute' });
} else {
$('#sticky').css({'top' : 'auto' });
}
};
Just building on Rich's answer, which uses offset.
I modified this as follows:
$sticky
in Rich's example, it wasn't doing anythingI've moved the offset check into a separate function, and called it on document ready as well as on scroll so if the page refreshes with the scroll half-way down the page, it resizes straight-away without having to wait for a scroll trigger
jQuery(document).ready(function($){
var offset = $( "#header" ).offset();
checkOffset();
$(window).scroll(function() {
checkOffset();
});
function checkOffset() {
if ( $(document).scrollTop() > offset.top){
$('#header').addClass('fixed');
} else {
$('#header').removeClass('fixed');
}
}
});
As a summary
import sys
import re
f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
s=myfile.read()
ret = re.sub(find,replace, s) # <<< This is where the magic happens
print ret
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
jQuery is a JavaScript library.
Read
wiki-jQuery, github, jQuery vs. javascript?
What is JQuery?
Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:
JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.
Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.
JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.
See here.
To remove all the documents in all the collections:
db.getCollectionNames().forEach( function(collection_name) {
if (collection_name.indexOf("system.") == -1) {
print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
db[collection_name].remove({});
}
});
This query is to convert the DateTimeOffset
into the format yyyyMMddhhss
with Offset. I have replaced the hyphens, colon(:), period(.)
from the data, and kept the hyphen for the seperation of Offset from the DateTime
.
SELECT REPLACE(SUBSTRING(CONVERT(VARCHAR(33),SYSDATETIMEOFFSET(),126), 1, 8), '-', '') +
SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126),'T',''),'.',''),':',''),9,DATALENGTH(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126)))
If choosing between OAuth versions, go with OAuth 2.0.
OAuth bearer tokens should only be used with a secure transport.
OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.
While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.
If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.
Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.
STATICFILES_DIRS
: You can keep the static files for your project here e.g. the ones used by your templates.
STATIC_ROOT
: leave this empty, when you do manage.py collectstatic
, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.
--------Edit----------------
As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
or
STATIC_ROOT = '/opt/web/project/static_files'
--------End Edit -----------------
STATIC_URL
: '/static/' is usually fine, it's just a prefix for static files.
mount -o rw,remount $(mount | grep /dev/root | awk '{print $3}')
this does the job for me, and should work for any android version.
You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:
functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design
Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.
Unless C: is not the drive that windows booted from.
Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\windows).
I am using JavaScript but some of the principles are common I am sure.
The code I am using is as follows:
var s = new webdriver.ActionSequence(d);
d.findElement(By.className('fc-time')).then(function(result){
s.mouseMove(result,l).click().perform();
});
the driver = d
.
The location = l
is simply {x:300,y:500)
- it is just an offset.
What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.
I suspect the figures in the locate are a bit more difficult to predict than I thought.
It is an old post but this response may help other newcomers like me.
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];
//I think this will work, you don't have to replace on the even, it's just an example.
public void emphasize(String phrase, char ch)
{
char phraseArray[] = phrase.toCharArray();
for(int i=0; i< phrase.length(); i++)
{
if(i%2==0)// even number
{
String value = Character.toString(phraseArray[i]);
value = value.replace(value,"*");
phraseArray[i] = value.charAt(0);
}
}
}
For completeness, in Numpy there are four maximum related functions. They fall into two different categories:
np.amax/np.max
, np.nanmax
: for single array order statisticsnp.maximum
, np.fmax
: for element-wise comparison of two arraysNaNs propagator np.amax/np.max
and its NaN ignorant counterpart np.nanmax
.
np.max
is just an alias of np.amax
, so they are considered as one function.
>>> np.max.__name__
'amax'
>>> np.max is np.amax
True
np.max
propagates NaNs while np.nanmax
ignores NaNs.
>>> np.max([np.nan, 3.14, -1])
nan
>>> np.nanmax([np.nan, 3.14, -1])
3.14
NaNs propagator np.maximum
and its NaNs ignorant counterpart np.fmax
.
Both functions require two arrays as the first two positional args to compare with.
# x1 and x2 must be the same shape or can be broadcast
np.maximum(x1, x2, /, ...);
np.fmax(x1, x2, /, ...)
np.maximum
propagates NaNs while np.fmax
ignores NaNs.
>>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([ nan, nan, 2.72])
>>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([-inf, 3.14, 2.72])
The element-wise functions are np.ufunc
(Universal Function), which means they have some special properties that normal Numpy function don't have.
>>> type(np.maximum)
<class 'numpy.ufunc'>
>>> type(np.fmax)
<class 'numpy.ufunc'>
>>> #---------------#
>>> type(np.max)
<class 'function'>
>>> type(np.nanmax)
<class 'function'>
And finally, the same rules apply to the four minimum related functions:
np.amin/np.min
, np.nanmin
; np.minimum
, np.fmin
.A Java constructor has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type, since constructors never return a value.
Constructor is always called when object is created. example:- Default constructor
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Here is an example of how to use strtok borrowed from MSDN.
And the relevant bits, you need to call it multiple times. The token
char* is the part you would stuff into an array (you can figure that part out).
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main( void )
{
printf( "Tokens:\n" );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
From the answers for the question System.Net.WebClient unreasonably slow
Try setting Proxy = null;
WebClient wc = new WebClient(); wc.Proxy = null;
Credit to Alex Burtsev
Few things to fix here:
Your code will look something like this
List<Answer> answers = new List<Answer>();
/* test
answers.Add(new Answer() { correct = false });
answers.Add(new Answer() { correct = true });
answers.Add(new Answer() { correct = false });
*/
Answer answer = answers.Single(a => a.correct == true);
and the class
class Answer
{
public bool correct;
}
Curious, what happens if you use straight net.sockets
instead? Here's some sample code I put together for testing purposes:
var net = require('net');
function HttpRequest(host, port, path, method) {
return {
headers: [],
port: 80,
path: "/",
method: "GET",
socket: null,
_setDefaultHeaders: function() {
this.headers.push(this.method + " " + this.path + " HTTP/1.1");
this.headers.push("Host: " + this.host);
},
SetHeaders: function(headers) {
for (var i = 0; i < headers.length; i++) {
this.headers.push(headers[i]);
}
},
WriteHeaders: function() {
if(this.socket) {
this.socket.write(this.headers.join("\r\n"));
this.socket.write("\r\n\r\n"); // to signal headers are complete
}
},
MakeRequest: function(data) {
if(data) {
this.socket.write(data);
}
this.socket.end();
},
SetupRequest: function() {
this.host = host;
if(path) {
this.path = path;
}
if(port) {
this.port = port;
}
if(method) {
this.method = method;
}
this._setDefaultHeaders();
this.socket = net.createConnection(this.port, this.host);
}
}
};
var request = HttpRequest("www.somesite.com");
request.SetupRequest();
request.socket.setTimeout(30000, function(){
console.error("Connection timed out.");
});
request.socket.on("data", function(data) {
console.log(data.toString('utf8'));
});
request.WriteHeaders();
request.MakeRequest();
I found part of the solution. Images now have metadata that specify the orientation of the photo. There is a new CSS spec for image-orientation
.
Just add this to your CSS:
img {
image-orientation: from-image;
}
According to the spec as of Jan 25 2016, Firefox and iOS Safari (behind a prefix) are the only browsers that support this. I'm seeing issues with Safari and Chrome still. However, mobile Safari seems to natively support orientation without the CSS tag.
I suppose we'll have to wait and see if browsers wills start supporting image-orientation
.
You could json encode a generic object.
$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);
Tried many utilities including mkpasswd, Python etc. But it seems like there is some compatibility issue with Ansible in reading HASH values generated by other tools. So finally it worked by ansible # value itself.
ansible all -i localhost, -m debug -a "msg={{ 'yourpasswd' | password_hash('sha512', 'mysecretsalt') }}"
Playbook -
- name: User creation
user:
name: username
uid: UID
group: grpname
shell: /bin/bash
comment: "test user"
password: "$6$mysecretsalt$1SMjoVXjYf.3sJR3a1WUxlDCmdJwC613.SUD4DOf40ASDFASJHASDFCDDDWERWEYbs8G00NHmOg29E0"
Restarting VSCode worked for me.
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
The problem is the background image on the html
element. You appear to have set it to "null" which is not valid. Try removing that CSS rule entirely, or at least setting background-image:none
EDIT: the CSS file says it is "generated" so I don't know exactly what you will be able to edit. The problem is this line:
html { background-color:null !important; background-position:null !important; background-repeat:repeat !important; background-image:url('http://images.freewebs.com/Images/null.gif') !important; }
I'm guessing you've put null as a value and it has set the background to a GIF called 'null'.
"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull
or git push
without arguments. A little bit down, this article explains and demonstrates this concept.
Multiple attributes can be connected with an and
:
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
(use find_or_initialize_by
if you don't want to save the record right away)
Edit: The above method is deprecated in Rails 4. The new way to do it will be:
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
and
GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
Edit 2: Not all of these were factored out of rails just the attribute specific ones.
https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md
Example
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
became
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
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>
Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.
To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):
Parser.new.methods - Object.new.methods
They both track your changes to the collection, just call the SaveChanges() method that should update the DB.
I got Broyden's method to work for coupled non-linear equations (generally involving polynomials and exponentials) in IDL, but I haven't tried it in Python:
scipy.optimize.broyden1
scipy.optimize.broyden1(F, xin, iter=None, alpha=None, reduction_method='restart', max_rank=None, verbose=False, maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, tol_norm=None, line_search='armijo', callback=None, **kw)[source]
Find a root of a function, using Broyden’s first Jacobian approximation.
This method is also known as “Broyden’s good method”.
In Asp.Net Core you can request the token directly, as documented:
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
And use it in javascript:
function DoSomething(id) {
$.post("/something/todo/"+id,
{ "__RequestVerificationToken": '@GetAntiXsrfRequestToken()' });
}
You can add the recommended global filter, as documented:
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})
Update
The above solution works in scripts that are part of the .cshtml. If this is not the case then you can't use this directly. My solution was to use a hidden field to store the value first.
My workaround, still using GetAntiXsrfRequestToken
:
When there is no form:
<input type="hidden" id="RequestVerificationToken" value="@GetAntiXsrfRequestToken()">
The name
attribute can be omitted since I use the id
attribute.
Each form includes this token. So instead of adding yet another copy of the same token in a hidden field, you can also search for an existing field by name
. Please note: there can be multiple forms inside a document, so name
is in that case not unique. Unlike an id
attribute that should be unique.
In the script, find by id:
function DoSomething(id) {
$.post("/something/todo/"+id,
{ "__RequestVerificationToken": $('#RequestVerificationToken').val() });
}
An alternative, without having to reference the token, is to submit the form with script.
Sample form:
<form id="my_form" action="/something/todo/create" method="post">
</form>
The token is automatically added to the form as a hidden field:
<form id="my_form" action="/something/todo/create" method="post">
<input name="__RequestVerificationToken" type="hidden" value="Cf..." /></form>
And submit in the script:
function DoSomething() {
$('#my_form').submit();
}
Or using a post method:
function DoSomething() {
var form = $('#my_form');
$.post("/something/todo/create", form.serialize());
}
I made the following 'universal' cross thread call class for my own purpose, but I think it's worth to share it:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace CrossThreadCalls
{
public static class clsCrossThreadCalls
{
private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);
public static void SetAnyProperty(Control c, string Property, object Value)
{
if (c.GetType().GetProperty(Property) != null)
{
//The given property exists
if (c.InvokeRequired)
{
SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);
c.BeginInvoke(d, c, Property, Value);
}
else
{
c.GetType().GetProperty(Property).SetValue(c, Value, null);
}
}
}
private delegate void SetTextPropertyCallBack(Control c, string Value);
public static void SetTextProperty(Control c, string Value)
{
if (c.InvokeRequired)
{
SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);
c.BeginInvoke(d, c, Value);
}
else
{
c.Text = Value;
}
}
}
And you can simply use SetAnyProperty() from another thread:
CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());
In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.
You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:
Any time you see varname =
, you're creating a new name binding within the function's scope. Whatever value varname
was bound to before is lost within this scope.
Any time you see varname.foo()
you're calling a method on varname
. The method may alter varname (e.g. list.append
). varname
(or, rather, the object that varname
names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.
[note that the global
keyword creates an exception to the first case]
Delete unversioned files and revert any changes:
svn revert D:\tmp\sql -R
svn cleanup D:\tmp\sql --remove-unversioned
Out:
D D:\tmp\sql\update\abc.txt
I think worth mentioning is, that a condition combined with logical AND/OR will not return a boolean value but last success or first fail in case of && and first success or last fail in case of || of condition chain.
res = (1 && 2); // res is 2
res = (true && alert) // res is function alert()
res = ('foo' || alert) // res is 'foo'
In order to cast the condition to a true boolean literal we can use the double negation:
res = !!(1 && 2); // res is true
res = !!(true && alert) // res is true
res = !!('foo' || alert) // res is true
I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !
https://github.com/aponxi/npm-execxi
ExecXI is a node extension written in C++ to execute shell commands one by one, outputting the command's output to the console in real-time. Optional chained, and unchained ways are present; meaning that you can choose to stop the script after a command fails (chained), or you can continue as if nothing has happened !
Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!
EDIT: However it doesn't return the stdout yet... Just outputs them in real-time. It does now. Well, I just released it today. Maybe we can build on it.
Anyway, I thought it was worth to mention it.
In the header file define a base class:
class BaseClass {
public:
BaseClass(params);
};
Then define a derived class as inheriting the BaseClass:
class DerivedClass : public BaseClass {
public:
DerivedClass(params);
};
In the source file define the BaseClass constructor:
BaseClass::BaseClass(params)
{
//Perform BaseClass initialization
}
By default the derived constructor only calls the default base constructor with no parameters; so in this example, the base class constructor is NOT called automatically when the derived constructor is called, but it can be achieved simply by adding the base class constructor syntax after a colon (:
). Define a derived constructor that automatically calls its base constructor:
DerivedClass::DerivedClass(params) : BaseClass(params)
{
//This occurs AFTER BaseClass(params) is called first and can
//perform additional initialization for the derived class
}
The BaseClass
constructor is called BEFORE the DerivedClass
constructor, and the same/different parameters params
may be forwarded to the base class if desired. This can be nested for deeper derived classes. The derived constructor must call EXACTLY ONE base constructor. The destructors are AUTOMATICALLY called in the REVERSE order that the constructors were called.
EDIT: There is an exception to this rule if you are inheriting from any virtual
classes, typically to achieve multiple inheritance or diamond inheritance. Then you MUST explicitly call the base constructors of all virtual
base classes and pass the parameters explicitly, otherwise it will only call their default constructors without any parameters. See: virtual inheritance - skipping constructors
I just copy pasted the database folders to data folder in MySQL, i.e. If you have a database called alto then find the folder alto in your MySQL -> Data folder in your backup and copy the entire alto folder and past it to newly installed MySQL -> data folder, restart the MySQL and this works perfect.
Press the hammer to the left of the green arrow (run), for the program to clean & build project. Press green arrow. Select Main Class.
Hope it works for u.
This error can occur in several places, most commonly running further LINQ queries on top of a null collection. LINQ as Query Syntax can appear more null-safe than it is. Consider the following samples:
var filteredCollection = from item in getMyCollection()
orderby item.ReportDate
select item;
This code is not NULL SAFE, meaning that if getMyCollection()
returns a null, you'll get the Value cannot be null. Parameter name: source
error. Very annoying! But it makes perfect sense because LINQ Query syntax is just syntactic sugar for this equivalent code:
var filteredCollection = getMyCollection().OrderBy(x => x.ReportDate);
Which obviously will blow up if the starting method returns a null.
To prevent this, you can use a null coalescing operator in your LINQ query like so:
var filteredCollection = from item in getMyCollection() ??
Enumerable.Empty<CollectionItemClass>()
orderby item.ReportDate
select item;
However, you'll have to remember to do this in any related queries. The best approach (if you control the code that generates the collection) is to make it a coding practice to NEVER RETURN A NULL COLLECTION, EVER. In some cases, returning a null object from a method like "getCustomerById(string id)
" is fine, depending on your team coding style, but if you have a method that returns a collection of business objects, like "getAllcustomers()
" then it should NEVER return a null array/enumerable/etc. Always always always use an if
check, the null coalescing operator, or some other switch to return an empty array/list/enumerable etc, so that consumers of your method can freely LINQ over the results.
Check out this site: http://rubular.com/ Basically the site allows you to enter some example text (what you would be looking for on your site) and then as you build the regular expression it will highlight what is being matched in real time.
Templates and other methods based on preliminary creation of the document in memory are likely to impose certain limits on resulting document size.
Meanwhile a very straightforward and reliable write-on-the-fly approach to creation of plain HTML exists, based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:
String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory saxFactory =
(SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);
Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
tHandler.startElement("", "", "html", new AttributesImpl());
tHandler.startElement("", "", "head", new AttributesImpl());
tHandler.startElement("", "", "title", new AttributesImpl());
tHandler.characters("Hello".toCharArray(), 0, 5);
tHandler.endElement("", "", "title");
tHandler.endElement("", "", "head");
tHandler.startElement("", "", "body", new AttributesImpl());
tHandler.startElement("", "", "p", new AttributesImpl());
tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
tHandler.endElement("", "", "p");
tHandler.endElement("", "", "body");
tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();
Note that XSLT transformer will release you from the burden of escaping special characters like >
, as it takes necessary care of it by itself.
And it is easy to wrap SAX methods like startElement()
and characters()
to something more convenient to one's taste...
Raw types are fine when they express what you want to express.
For example, a deserialisation function might return a List
, but it doesn't know the list's element type. So List
is the appropriate return type here.
Collections.synchronizedMap()
guarantees that each atomic operation you want to run on the map will be synchronized.
Running two (or more) operations on the map however, must be synchronized in a block. So yes - you are synchronizing correctly.
I used all of the above answers and none worked. This answer works for API 21+. Use app:hintTextColor attribute when text field is focused and app:textColorHint attribute when in other states. To change the bottmline color use this attribute app:boxStrokeColor as demonstrated below:
<com.google.android.material.textfield.TextInputLayout
app:boxStrokeColor="@color/colorAccent"
app:hintTextColor="@color/colorAccent"
android:textColorHint="@android:color/darker_gray"
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
It works for AutoCompleteTextView as well. Hope it works for you:)
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
This stored procedure inserts a rand number into a table. Look out, it inserts an endless numbers. Stop executing it when u get enough numbers.
create a table for the cursor:
CREATE TABLE [dbo].[SearchIndex](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Cursor] [nvarchar](255) NULL)
GO
Create a table to contain your numbers:
CREATE TABLE [dbo].[ID](
[IDN] [int] IDENTITY(1,1) NOT NULL,
[ID] [int] NULL)
INSERTING THE SCRIPT :
INSERT INTO [SearchIndex]([Cursor]) SELECT N'INSERT INTO ID SELECT FLOOR(rand() * 9 + 1) SELECT COUNT (ID) FROM ID
CREATING AND EXECUTING THE PROCEDURE:
CREATE PROCEDURE [dbo].[RandNumbers] AS
BEGIN
Declare CURSE CURSOR FOR (SELECT [Cursor] FROM [dbo].[SearchIndex] WHERE [Cursor] IS NOT NULL)
DECLARE @RandNoSscript NVARCHAR (250)
OPEN CURSE
FETCH NEXT FROM CURSE
INTO @RandNoSscript
WHILE @@FETCH_STATUS IS NOT NULL
BEGIN
Print @RandNoSscript
EXEC SP_EXECUTESQL @RandNoSscript;
END
END
GO
Fill your table:
EXEC RandNumbers
You may want to confirm that your development environment has been set correctly.
Quoting from spring.io:
Set up the Android development environment
Before you can build Android applications, you must install the Android SDK. Installing the Android SDK also installs the AVD Manager, a graphical user interface for creating and managing Android Virtual Devices (AVDs).
From the Android web site, download the correct version of the Android SDK for your operating system.
Unzip the archive to a location of your choosing. For example, on Linux or Mac, you can place it in the root of your user directory. See the Android Developers web site for additional installation details.
Configure the
ANDROID_HOME
environment variable based on the location of the Android SDK. Additionally, consider addingANDROID_HOME/tools
, andANDROID_HOME/platform-tools
to your PATH.Mac OS X
export ANDROID_HOME=/<installation location>/android-sdk-macosx export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Linux
export ANDROID_HOME=/<installation location>/android-sdk-linux export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Windows
set ANDROID_HOME=C:\<installation location>\android-sdk-windows set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools
The Android SDK download does not include specific Android platforms. To run the code in this guide, you need to download and install the latest SDK platform. You do this by using the Android SDK and AVD Manager that you installed in the previous section.
Open the Android SDK Manager window:
android
Note: If this command does not open the Android SDK Manager, then your path is not configured correctly.
Select the Tools checkbox.
Select the checkbox for the latest Android SDK.
From the Extras folder, select the checkbox for the Android Support Library.
Click the Install packages... button to complete the download and installation.
Note: You may want to install all the available updates, but be aware it will take longer, as each API level is a large download.
The xpath() function does not return a string. It returns an array with XML elements (of type SimpleXMLElement
), which may be casted to a string.
if (count($message)) {
if (strlen((string)$message[0]) < 141) {
echo "There Are No Contests.";
}
else if(strlen((string)$message[0]) > 142) {
echo "There is One Active Contest.";
}
}
The code from the accepted answer helped me to debug the issue. I then realized that the SN field of the certificate
argument wasn't the same as what I thought was my SMTP server. By setting the Host
property of the SmtpClient instance to the SN value of the certificate I was able to fix the issue.
your form is missing the method...
<form name="registrationform" action="register.php" method="post"> //here
anywyas to check the posted data u can use isset()..
Determine if a variable is set and is not NULL
if(!isset($firstname) || trim($firstname) == '')
{
echo "You did not fill out the required fields.";
}
Why not use reduce so that we can take colspan into account? :)
function getColumns(table) {
var cellsArray = [];
var cells = table.rows[0].cells;
// Cast the cells to an array
// (there are *cooler* ways of doing this, but this is the fastest by far)
// Taken from https://stackoverflow.com/a/15144269/6424295
for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);
return cellsArray.reduce(
(cols, cell) =>
// Check if the cell is visible and add it / ignore it
(cell.offsetParent !== null) ? cols += cell.colSpan : cols,
0
);
}
Like @itsneo said, I personally find ? + [ and ] the most convenient ones on a mac. But I can understand if you come from Linux side of things. Then you can use ? + alt + ? or ?.
You're looking for Select
which can be used to transform\project the input sequence:
IEnumerable<string> strings = integers.Select(i => i.ToString());
If you want a more accurate measurement than the answer above:
set statistics time on
-- Query 1 goes here
-- Query 2 goes here
set statistics time off
The results will be in the Messages window.
Update (2015-07-29):
By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats
that may also be of value:
-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.
-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';
SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0))
AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
(OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
(DB_NAME(database_id)=@DbName OR @DbName IS NULL)
Don't. Leave them as Java and use IKVM to convert them to .Net DLLs.
If you want to turn off logging programmatically then use
List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
logger.setLevel(Level.OFF);
}
fwiw, I received this error due to some custom initialization within the constructor attempting to access a null object.
To read a file line by line (also for extreme big files) can be done by the following functions:
DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile];
NSString * line = nil;
while ((line = [reader readLine])) {
NSLog(@"read line: %@", line);
}
[reader release];
Or:
DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile];
[reader enumerateLinesUsingBlock:^(NSString * line, BOOL * stop) {
NSLog(@"read line: %@", line);
}];
[reader release];
The class DDFileReader that enables this is the following:
Interface File (.h):
@interface DDFileReader : NSObject {
NSString * filePath;
NSFileHandle * fileHandle;
unsigned long long currentOffset;
unsigned long long totalFileLength;
NSString * lineDelimiter;
NSUInteger chunkSize;
}
@property (nonatomic, copy) NSString * lineDelimiter;
@property (nonatomic) NSUInteger chunkSize;
- (id) initWithFilePath:(NSString *)aPath;
- (NSString *) readLine;
- (NSString *) readTrimmedLine;
#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL *))block;
#endif
@end
Implementation (.m)
#import "DDFileReader.h"
@interface NSData (DDAdditions)
- (NSRange) rangeOfData_dd:(NSData *)dataToFind;
@end
@implementation NSData (DDAdditions)
- (NSRange) rangeOfData_dd:(NSData *)dataToFind {
const void * bytes = [self bytes];
NSUInteger length = [self length];
const void * searchBytes = [dataToFind bytes];
NSUInteger searchLength = [dataToFind length];
NSUInteger searchIndex = 0;
NSRange foundRange = {NSNotFound, searchLength};
for (NSUInteger index = 0; index < length; index++) {
if (((char *)bytes)[index] == ((char *)searchBytes)[searchIndex]) {
//the current character matches
if (foundRange.location == NSNotFound) {
foundRange.location = index;
}
searchIndex++;
if (searchIndex >= searchLength) { return foundRange; }
} else {
searchIndex = 0;
foundRange.location = NSNotFound;
}
}
return foundRange;
}
@end
@implementation DDFileReader
@synthesize lineDelimiter, chunkSize;
- (id) initWithFilePath:(NSString *)aPath {
if (self = [super init]) {
fileHandle = [NSFileHandle fileHandleForReadingAtPath:aPath];
if (fileHandle == nil) {
[self release]; return nil;
}
lineDelimiter = [[NSString alloc] initWithString:@"\n"];
[fileHandle retain];
filePath = [aPath retain];
currentOffset = 0ULL;
chunkSize = 10;
[fileHandle seekToEndOfFile];
totalFileLength = [fileHandle offsetInFile];
//we don't need to seek back, since readLine will do that.
}
return self;
}
- (void) dealloc {
[fileHandle closeFile];
[fileHandle release], fileHandle = nil;
[filePath release], filePath = nil;
[lineDelimiter release], lineDelimiter = nil;
currentOffset = 0ULL;
[super dealloc];
}
- (NSString *) readLine {
if (currentOffset >= totalFileLength) { return nil; }
NSData * newLineData = [lineDelimiter dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle seekToFileOffset:currentOffset];
NSMutableData * currentData = [[NSMutableData alloc] init];
BOOL shouldReadMore = YES;
NSAutoreleasePool * readPool = [[NSAutoreleasePool alloc] init];
while (shouldReadMore) {
if (currentOffset >= totalFileLength) { break; }
NSData * chunk = [fileHandle readDataOfLength:chunkSize];
NSRange newLineRange = [chunk rangeOfData_dd:newLineData];
if (newLineRange.location != NSNotFound) {
//include the length so we can include the delimiter in the string
chunk = [chunk subdataWithRange:NSMakeRange(0, newLineRange.location+[newLineData length])];
shouldReadMore = NO;
}
[currentData appendData:chunk];
currentOffset += [chunk length];
}
[readPool release];
NSString * line = [[NSString alloc] initWithData:currentData encoding:NSUTF8StringEncoding];
[currentData release];
return [line autorelease];
}
- (NSString *) readTrimmedLine {
return [[self readLine] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL*))block {
NSString * line = nil;
BOOL stop = NO;
while (stop == NO && (line = [self readLine])) {
block(line, &stop);
}
}
#endif
@end
The class was done by Dave DeLong
You can also use the provided CLI tool mysqlcheck
to run the optimizations. It's got a ton of switches but at its most basic you just pass in the database, username, and password.
Adding this to cron or the Windows Scheduler can make this an automated process. (MariaDB but basically the same thing.)
The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:
/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
color: #fff;
background-color: #0495c9;
border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
color: #fff;
background-color: #00b3db;
border-color: #285e8e; /*set the color you want here*/
}
If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
with open("./404.csv", "a") as f:
f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
this is the answer async at console app in C#?
anything whereever in the console app never use await
but instead use theAsyncMethod().GetAwaiter().GetResult();
,
example
var result = await HttpClientInstance.SendAsync(message);
becomes
var result = HttpClientInstance.SendAsync(message).GetAwaiter().GetResult();
If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the "sh -n" or "bash -n" commands (see other answers) in a variable, and have a "if/else" based on that
bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \; 2>&1 > /dev/null)
if [ "$bashErrLines" != "" ]; then
# at least one sh file in the bin dir has a syntax error
echo $bashErrLines;
exit;
fi
Change "sh" with "bash" depending on your needs
If you need only make and friends. Try installing the command-line-tools provided by Apple. (Assuming you are not doing any iOS development.)
The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.
Open a PowerShell check what it is called using SqlLocalDB.exe info
and whether it is Running with SqlLocalDB.exe info NAME
. Here's what it looks like on my machine:
> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name: mssqllocaldb
Version: 13.0.1601.5
Shared name:
Owner: DESKTOP-I4H3E09\simon
Auto-create: Yes
State: Running
Last start time: 4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>
If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB
. When it is running you see the Instance pipe name:
which starts with np:\\
. Copy that named pipe string. Within VS2017 open the view Server Explorer
and create a new connection of type Microsoft SQL Server (SqlClient)
(don't be fooled by the other file types you want the full fat connection type) and set the Server name:
to be the instance pipe name you copied from PowerShell.
I also set the Connect to database
to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update
.
You can login and create a database using the sqlcmd
and the named pipe string:
sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query
1> create database EFGetStarted.ConsoleApp.NewDb;
2> GO
There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility
Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv
and paste the following content.
Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no
Here is the code the comments explains everything we are doing here! [python]
import pandas as pd
import pprint
class Classifier():
data = None
class_attr = None
priori = {}
cp = {}
hypothesis = None
def __init__(self,filename=None, class_attr=None ):
self.data = pd.read_csv(filename, sep=',', header =(0))
self.class_attr = class_attr
'''
probability(class) = How many times it appears in cloumn
__________________________________________
count of all class attribute
'''
def calculate_priori(self):
class_values = list(set(self.data[self.class_attr]))
class_data = list(self.data[self.class_attr])
for i in class_values:
self.priori[i] = class_data.count(i)/float(len(class_data))
print "Priori Values: ", self.priori
'''
Here we calculate the individual probabilites
P(outcome|evidence) = P(Likelihood of Evidence) x Prior prob of outcome
___________________________________________
P(Evidence)
'''
def get_cp(self, attr, attr_type, class_value):
data_attr = list(self.data[attr])
class_data = list(self.data[self.class_attr])
total =1
for i in range(0, len(data_attr)):
if class_data[i] == class_value and data_attr[i] == attr_type:
total+=1
return total/float(class_data.count(class_value))
'''
Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
(Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
scaled by P(Multiple Evidence)
'''
def calculate_conditional_probabilities(self, hypothesis):
for i in self.priori:
self.cp[i] = {}
for j in hypothesis:
self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
print "\nCalculated Conditional Probabilities: \n"
pprint.pprint(self.cp)
def classify(self):
print "Result: "
for i in self.cp:
print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]
if __name__ == "__main__":
c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
c.calculate_priori()
c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
c.calculate_conditional_probabilities(c.hypothesis)
c.classify()
output:
Priori Values: {'yes': 0.6428571428571429, 'no': 0.35714285714285715}
Calculated Conditional Probabilities:
{
'no': {
'<=30': 0.8,
'fair': 0.6,
'medium': 0.6,
'yes': 0.4
},
'yes': {
'<=30': 0.3333333333333333,
'fair': 0.7777777777777778,
'medium': 0.5555555555555556,
'yes': 0.7777777777777778
}
}
Result:
yes ==> 0.0720164609053
no ==> 0.0411428571429
Hope it helps in better understanding the problem
peace
I also got the same issue with chrome, after adding DOCTYPE
it works as expected
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
Before
<?xml version="1.0" encoding="iso-8859-1"?>
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
<g fill="none" stroke="black" stroke-width="15">
......
......
.......
</g>
</svg>
After
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
<g fill="none" stroke="black" stroke-width="15">
......
......
.......
</g>
</svg>
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link
Here is my solution to split a file called patch6.txt (about 32,000 lines) into separate files of 1000 lines each. Its not quick, but it does the job.
$infile = "D:\Malcolm\Test\patch6.txt"
$path = "D:\Malcolm\Test\"
$lineCount = 1
$fileCount = 1
foreach ($computername in get-content $infile)
{
write $computername | out-file -Append $path_$fileCount".txt"
$lineCount++
if ($lineCount -eq 1000)
{
$fileCount++
$lineCount = 1
}
}
When you upload a file using FileField
, the file will have a URL that you can use to point to the file and use HTML download
attribute to download that file you can simply do this.
models.py
The model.py looks like this
class CsvFile(models.Model):
csv_file = models.FileField(upload_to='documents')
views.py
#csv upload
class CsvUploadView(generic.CreateView):
model = CsvFile
fields = ['csv_file']
template_name = 'upload.html'
#csv download
class CsvDownloadView(generic.ListView):
model = CsvFile
fields = ['csv_file']
template_name = 'download.html'
Then in your templates.
#Upload template
upload.html
<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>
#download template
download.html
{% for document in object_list %}
<a href="{{ document.csv_file.url }}" download class="btn btn-dark float-right">Download</a>
{% endfor %}
I did not use forms, just rendered model but either way, FileField is there and it will work the same.
You can try and do this:
tryTrans = string.maketrans(",!", " ")
str = "This is a string, with words!"
str = str.translate(tryTrans)
listOfWords = str.split()
TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])
You may test if a string is convertible to integer by using boost::lexical_cast. If it throws bad_lexical_cast exception then string could not be converted, otherwise it can.
See example of such a test program below:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main(int, char** argv)
{
try
{
int x = boost::lexical_cast<int>(argv[1]);
std::cout << x << " YES\n";
}
catch (boost::bad_lexical_cast const &)
{
std:: cout << "NO\n";
}
return 0;
}
Sample execution:
# ./a.out 12
12 YES
# ./a.out 12/3
NO
I'd suggest to use .nth(0)
rather than .first()
if you need to get the first row.
The difference between them is how they handle NaNs, so .nth(0)
will return the first row of group no matter what are the values in this row, while .first()
will eventually return the first not NaN
value in each column.
E.g. if your dataset is :
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
'value' : ["first","second","third", np.NaN,
"second","first","second","third",
"fourth","first","second"]})
>>> df.groupby('id').nth(0)
value
id
1 first
2 NaN
3 first
4 first
And
>>> df.groupby('id').first()
value
id
1 first
2 second
3 first
4 first
Use the code
x = seq(0,100,5) #this means (starting number, ending number, interval)
the output will be
[1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
[17] 80 85 90 95 100
You can make use of
display: flex;
align-items: center;
justify-content: center;
on your parent component
XmlDocument.Attributes
perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)
Using the GCC compiler(which I did locally) and an online compiler(link), a code similar to the one in the question runs provided a variable name.
#include<iostream>
int main(){
int r= 2, c=3;
int arr[r][c];
arr[0][1]= 3;
std::cout<<arr[0][1];
}
Output: 3
Though I quote cplusplus.com,
NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression since arrays are blocks of static memory whose size must be determined at compile-time before the program runs.
It seems like the present compilers have been changed in this regard. This is a C99 standard which the maintainers of the standard compilers added to their compilers.
We need not have a const declaration. During compilation, the compiler automatically substitutes the value.
This question goes around the topic.
NOTE: This is not the standard coding practice, so some compilers might still throw an error.
To stick with the Maven terms:
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference
It's just a syntax error. You just have to replace j+3
by j=j+3
or j+=3
.
For android version 5.0 & above
try the Elevation for other views..
android:elevation="10dp"
For Buttons,
android:stateListAnimator="@anim/button_state_list_animator"
button_state_list_animator.xml - https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/anim/button_state_list_anim_material.xml
below 5.0 version,
For all views,
android:background="@android:drawable/dialog_holo_light_frame"
My output:
If you want to use rollback, then use start transaction and otherwise forget all those things,
By default, MySQL automatically commits the changes to the database.
To force MySQL not to commit these changes automatically, execute following:
SET autocommit = 0;
//OR
SET autocommit = OFF
To enable the autocommit mode explicitly:
SET autocommit = 1;
//OR
SET autocommit = ON;
You should install this Apache mod, http://httpd.apache.org/docs/2.0/mod/mod_info.html, it basically gives you a run down of the mods you're using and the Apache settings. I have this enabled on my Apache and it gives me this info for my website,
Server Version: Apache/2.2.3 (Debian) mod_jk/1.2.18 PHP/5.2.0-8+etch13 mod_ssl/2.2.3 OpenSSL/0.9.8c mod_perl/2.0.2 Perl/v5.8.8
You didn't select post_id
in the subquery. You have to select it in the subquery like this:
SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM wp_woocommerce_order_items
LEFT JOIN
(
SELECT meta_value As Prenom, post_id -- <----- this
FROM wp_postmeta
WHERE meta_key = '_shipping_first_name'
) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE wp_woocommerce_order_items.order_id =2198
What onetrickpony
posted is okay, but if you want to have a more general solution, you can just use the code below.
Instead of selecting just the id
of the anchor, you can make it bit more standard-like and just selecting the attribute name
of the <a>
-Tag. This will save you from writing an extra id
tag. Just add the smoothscroll class to the navbar element.
What changed
1) $('#nav ul li a[href^="#"]')
to $('#nav.smoothscroll ul li a[href^="#"]')
2) $(this.hash)
to $('a[name="' + this.hash.replace('#', '') + '"]')
Final Code
/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
I think I got it at last by doing some manual transformations with the data before visualization:
d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)
And work out a formatter to later compute 'back' the logarithmic data:
formatBack <- function(x) 10^x
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ')
And draw the plot with given formatter:
m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')
Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.
Anyway, thanks to @DWin for motivation!
null
is a value assigned to a reference type. null
is a reserved value, indicating that a reference does not resemble an instance of an object.
A boolean
is not an instance of an Object. It is a primitive type, like int
and float
. In the same way that: int x
has a value of 0
, boolean x
has a value of false
.
The traditional way to flag a method so that it will appear in Interface Builder, and you can drag a connection to it, has been to make the method return type IBAction. However, if you make your method void, instead (IBAction is #define'd to be void), and provide an (id) argument, the method is still visible. This provides extra flexibility, al
All 3 of these are visible from Interface Builder:
-(void) someMethod1:(id) sender;
-(IBAction) someMethod2;
-(IBAction) someMethod3:(id) sender;
See Apple's Interface Builder User Guide for details, particularly the section entitled Xcode Integration.
On GitHub, you can use HTML directly instead of Markdown:
<a href="url"><img src="http://url.to/image.png" align="left" height="48" width="48" ></a>
This should make it.
--save-dev: Package will appear in your devDependencies.
According to the npm install docs.
If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.
In other words, when you run npm install
, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).
According to the package.json docs
npm install
does:Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
I created a simple Objective C wrapper around the good old C array to be used more conveniently: https://gist.github.com/4705733
Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en
Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.
This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.
I wish you good luck of cause with your applications guys but be careful.
an alternative would be to do something like:
SELECT
CAST(P0.seconds as bigint) as seconds
FROM
(
SELECT
seconds
FROM
TableName
WHERE
ISNUMERIC(seconds) = 1
) P0
I found this blog post which cleared up a few things. To quote the most relevant bit:
Mixed Active Content is now blocked by default in Firefox 23!
What is Mixed Content?
When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.
The resolution, in my case, was to simply ensure the jquery
includes were as follows (note the removal of the protocol):
<link rel="stylesheet" href="//code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css" type="text/css">
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>
Note that the temporary 'fix' is to click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page', although this is not recommended for obvious reasons.
UPDATE: This link from the Firefox (Mozilla) support pages is also useful in explaining what constitutes mixed content and, as given in the above paragraph, does actually provide details of how to display the page regardless:
Most websites will continue to work normally without any action on your part.
If you need to allow the mixed content to be displayed, you can do that easily:
Click the shield icon Mixed Content Shield in the address bar and choose Disable Protection on This Page from the dropdown menu.
The icon in the address bar will change to an orange warning triangle Warning Identity Icon to remind you that insecure content is being displayed.
To revert the previous action (re-block mixed content), just reload the page.
See: http://www.postgresql.org/docs/9.1/static/arrays.html
If your non-native driver still does not allow you to pass arrays, then you can:
pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array
)
CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$
DECLARE
ids INT[];
BEGIN
ids = string_to_array($1,',');
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(:1)
with :1 = '1,2,3,4'
rely on Postgres itself to cast from a string to an array
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method('{1,2,3,4}')
choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(ARRAY [1,2,3,4])
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
If you've got all the plugin JS's imported and in the correct order, but you're still having issues, it seems that specifying your own "add" handler nerfs the one from the *-validate.js plugin, which normally would fire off all the validation by calling data.process(). So to fix it just do something like this in your "add" event handler:
$('#whatever').fileupload({
...
add: function(e, data) {
var $this = $(this);
data.process(function() {
return $this.fileupload('process', data);
}).done(function(){
//do success stuff
data.submit(); <-- fire off the upload to the server
}).fail(function() {
alert(data.files[0].error);
});
}
...
});
So, my case was the following. I didn't use proxy for the client-server interaction, I used ChannelFactory (thus all the advice to upgrade to service reference was meaningless to me).
The service was hosted in IIS and for some reason it had wrong references in the bin folder there. The project recompilation simply didn't lead to new dlls in that folder.
So I just deleted all the stuff from there and added reference to the service in the same solution, then recompiled and now everything works.
It is something concerned with the graphics drivers. If you update them you will be fine.
Or you can disable the hardware graphics acceleration in Visual Studio according to these steps:
In Visual Studio, click "Tools", and then click "Options".
In the Options dialog box, navigate to the "Environment > General" section and clear the "Automatically adjust visual experience based on client performance" check box. (Refer to the following screen shot for this step.)
Clear the "Use hardware graphics acceleration if available" check box to prevent the use of hardware graphics acceleration.
Select or clear the "Enable rich client visual experience" check box to make sure that rich visuals are always on or off, respectively. When this check box is selected, rich visuals are used independent of the computer environment. For example, rich visuals are used when you run Visual Studio locally on a rich client and over remote desktop.
References:
We had the same issue while trying to launch Selenium tests from Jenkins. I had selected the 'Start Xvfb before the build, and shut it down after' box and passed in the necessary screen options, but I was still getting this error.
It finally worked when we passed in the following commands in the Execute Shell box.
Xvfb :99 -ac -screen 0 1280x1024x24 &
nice -n 10 x11vnc 2>&1 &
...
killall Xvfb
As of CMake 3.1+ the developers strongly discourage users from using file(GLOB
or file(GLOB_RECURSE
to collect lists of source files.
Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.
See the documentation here.
There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.
It is possible. E.g. with file(GLOB
:
cmake_minimum_required(VERSION 2.8)
file(GLOB helloworld_SRC
"*.h"
"*.cpp"
)
add_executable(helloworld ${helloworld_SRC})
Note that this requires manual re-running of cmake
if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.
As of CMake 3.12, you can pass the CONFIGURE_DEPENDS
flag to file(GLOB
to automatically check and reset the file lists any time the build is invoked. You would write:
cmake_minimum_required(VERSION 3.12)
file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")
This at least lets you avoid manually re-running CMake every time a file is added.
Perhaps this works for you?
It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.
var myNumber = '50';
function addCommaStripe(text){
if(/,/.test(text) == false){
return text += ',-';
} else {
return text;
}
}
myNumber = addCommaStripe(myNumber);
Eric pretty much nailed it. We (Bitnami) are a popular provider of free AMIs for popular applications and development frameworks (PHP, Joomla, Drupal, you get the idea). I can tell you that EBS-backed AMIs are significantly more popular than S3-backed. In general I think s3-backed instances are used for distributed, time-limited jobs (for example, large scale processing of data) where if one machine fails, another one is simply spinned up. EBS-backed AMIS tend to be used for 'traditional' server tasks, such as web or database servers that keep state locally and thus require the data to be available in the case of crashing.
One aspect I did not see mentioned is the fact that you can take snapshots of an EBS-backed instance while running, effectively allowing you to have very cost-effective backups of your infrastructure (the snapshots are block-based and incremental)
nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size
by sending a 413 response and closing the connection.
Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.
If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue
header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large
response rather than 100 Continue
if Content-Length
exceeds the maximum body size.
Modify "Workspace.xml" (press Ctrl + Shft + R to search it)
Modify the activity name with package name
Make sure to change "name="USE_COMMAND_LINE" to value="false"
Reload the project
Done!
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.
As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.
Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.
As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).
Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.
The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.
__init_subclass__
As other answer mentioned you can check the __subclasses__
attribute to get the list of subclasses, since python 3.6 you can modify this attribute creation by overriding the __init_subclass__
method.
class PluginBase:
subclasses = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.subclasses.append(cls)
class Plugin1(PluginBase):
pass
class Plugin2(PluginBase):
pass
This way, if you know what you're doing, you can override the behavior of of __subclasses__
and omit/add subclasses from this list.
Notice the data-type and size
>describe all_tab_columns
VIEW all_tab_columns
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
Explicitly adding a npm version to file package.json ("npm": "1.1.x") and not checking in folder node_modules to Git worked for me.
It may be slower to deploy (since it downloads the packages each time), but I couldn't get the packages to compile when they were checked in. Heroku was looking for files that only existed on my local box.
You can use LOAD DATA INFILE command to import csv file into table.
Check this link MySQL - LOAD DATA INFILE.
LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);
For MySQL 8.0 users:
Using the LOCAL
keyword hold security risks and as of MySQL 8.0 the LOCAL
capability is set to False
by default. You might see the error:
ERROR 1148: The used command is not allowed with this MySQL version
You can overwrite it by following the instructions in the docs. Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.
You will have to use something like below
#menu ul{_x000D_
list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>First menu item</li>_x000D_
<li>Second menu item</li>_x000D_
<li>Third menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
As link-only answers are not preferred, I will just copy and paste the content of the link of the accepted answer
Which Log file? Well -- you can check the physical path by right-clicking on the System Log (e.g. Server Manager | Diagnostics | Event Viewer | Windows Logs). The default physical path is %SystemRoot%\System32\Winevt\Logs\System.evtx
.
You can create a Custom Filter and filter by "Source: WAS" to quickly see only entries generated by IIS.
You may need first to enable logging of such even for a specific App Pool -- by default App Pool has only 3 recycle events out of 8 enabled. To change it using GUI: II S Manager | Application Pools | Select App Pool -> Advanced Settings | Generate Recycle Event Log Entry.
Check for the SendCommand tool.
You can use it as follows:
perl sendcommand.pl -i login.txt -t cisco -c "show ip route"
When you want to show an URL of remote branches, try:
git remote -v
Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use
process.env[v]
.
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
Use the PropertyConfigurator: PropertyConfigurator.configure(configFileUrl);
To disable close button you should add the following code to your Window class (the code was taken from here, edited and reformatted a bit):
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
{
hwndSource.AddHook(HwndSourceHook);
}
}
private bool allowClosing = false;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
private const uint MF_BYCOMMAND = 0x00000000;
private const uint MF_GRAYED = 0x00000001;
private const uint SC_CLOSE = 0xF060;
private const int WM_SHOWWINDOW = 0x00000018;
private const int WM_CLOSE = 0x10;
private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_SHOWWINDOW:
{
IntPtr hMenu = GetSystemMenu(hwnd, false);
if (hMenu != IntPtr.Zero)
{
EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
}
}
break;
case WM_CLOSE:
if (!allowClosing)
{
handled = true;
}
break;
}
return IntPtr.Zero;
}
This code also disables close item in System menu and disallows closing the dialog using Alt+F4.
You will probably want to close the window programmatically. Just calling Close()
will not work. Do something like this:
allowClosing = true;
Close();
Do not use TinyXML if you're concerned about efficiency/memory management (it tends to allocate lots of tiny blocks). My personal favourite is RapidXML.
We were getting this same error in Fiddler when trying to figure out why our Silverlight ArcGIS map viewer wasn't loading the map.
In our case it was a typo in the URL in the code. There was an equal sign in there for some reason.
http:=//someurltosome/awesome/place
instead of
http://someurltosome/awesome/place
After taking out that equal sign it worked great (of course).
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
As doc says also keep in mind the correct value combination:
The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:
<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >
There is a combination of techniques which I found useful in solving this issue:
with open(file, 'r+') as fd:
contents = fd.readlines()
contents.insert(index, new_string) # new_string should end in a newline
fd.seek(0) # readlines consumes the iterator, so we need to start over
fd.writelines(contents) # No need to truncate as we are increasing filesize
In our particular application, we wanted to add it after a certain string:
with open(file, 'r+') as fd:
contents = fd.readlines()
if match_string in contents[-1]: # Handle last line to prevent IndexError
contents.append(insert_string)
else:
for index, line in enumerate(contents):
if match_string in line and insert_string not in contents[index + 1]:
contents.insert(index + 1, insert_string)
break
fd.seek(0)
fd.writelines(contents)
If you want it to insert the string after every instance of the match, instead of just the first, remove the else:
(and properly unindent) and the break
.
Note also that the and insert_string not in contents[index + 1]:
prevents it from adding more than one copy after the match_string
, so it's safe to run repeatedly.
We can separate out section of which we need to convert in PDF
For example, if table is in class "pdf-table-wrap"
After this, we need to call html2canvas function combined with jsPDF
following is sample code
var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
onrendered: function(canvas) {
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));
}
});
setTimeout(function() {
//jsPDF code to save file
pdf.save('sample.pdf');
}, 0);
Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/
First, you should disable selinux
, edit file /etc/sysconfig/selinux
so it looks like this:
SELINUX=disabled
SELINUXTYPE=targeted
Save file and restart system.
Then you can add the new rule to iptables
:
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
and restart iptables with /etc/init.d/iptables restart
If it doesn't work you should check other network settings.
It is not necessary to stop timer, see nice solution from this post:
"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."
private void CreatorLoop(object state)
{
if (Monitor.TryEnter(lockObject))
{
try
{
// Work here
}
finally
{
Monitor.Exit(lockObject);
}
}
}
You could use groupby
to split the DataFrame into subgroups according to the color:
for key, grp in df.groupby(['color']):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()
for key, grp in df.groupby(['color']):
ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)
plt.legend(loc='best')
plt.show()
yields
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseAssuming you are using this for a web service, you can just apply the following attribute to the class:
[System.Web.Script.Services.ScriptService]
Then the following attribute to each method that should return Json:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
And set the return type for the methods to be "object"
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
You could use @> operator to do this something like
SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';
public static void main(String[] args){
String string = "elamparuthi, elam, elamparuthi";
String[] s = string.replace(" ", "").split(",");
String[] op;
String ops = "";
for(int i=0; i<=s.length-1; i++){
if(!ops.contains(s[i]+"")){
if(ops != "")ops+=", ";
ops+=s[i];
}
}
System.out.println(ops);
}
Try with this
SELECT top 1 id, Col2, row_number() over (order by id desc) FROM Table
General rule is that you want packages from require-dev section only in development (dev) environments, for example local environment.
Packages in require-dev section are packages which help you debug app, run tests etc.
At staging and production environment you probably want only packages from require section.
But anyway you can run composer install --no-dev and composer update --no-dev on any environment, command will install only packages from required section not from require-dev, but probably you want to run this only at staging and production environments not on local.
Theoretically you can put all packages in require section and nothing will happened, but you don't want developing packages at production environment because of the following reasons :
Some good candidates for require-dev are :
"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"
you can see what above packages are doing and you will see why you don't need them on production.
See more here : https://getcomposer.org/doc/04-schema.md