For user check, just post get the access token as accessToken and post it and get the response
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken
you can try in address bar in browsers too, use httppost and response in java also
response will be like
{
"issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
"scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
"expires_in": 3340,
"access_type": "offline"
}
The scope is the given permission of the accessToken. you can check the scope ids in this link
Update: New API post as below
https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123
Response will be as
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "[email protected]",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}
For more info, https://developers.google.com/identity/sign-in/android/backend-auth
I think that you can do something like this:
let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');
It worked for me.
It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.
https://github.com/davidjbradshaw/iframe-resizer
It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.
Works in all modern browsers and IE8 upwards.
Or, alternatively, you can take a list comprehension
approach:
>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.
SELECT wpoi.order_id As No_Commande
FROM wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id
AND wpp.meta_key = '_shipping_first_name'
WHERE wpoi.order_id =2198
I would emphasize the importance of limiting the ::ng-deep
to only children of a component by requiring the parent to be an encapsulated css class.
For this to work it's important to use the ::ng-deep
after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.
Using the :host
keyword before ::ng-deep
will handle this automatically:
:host ::ng-deep .mat-checkbox-layout
Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep
keyword:
.my-component ::ng-deep .mat-checkbox-layout {
background-color: aqua;
}
Component template:
<h1 class="my-component">
<mat-checkbox ....></mat-checkbox>
</h1>
Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:
.my-component[_ngcontent-c1] .mat-checkbox-layout {
background-color: aqua;
}
The only difference is that CHARACTER VARYING is more human friendly than VARCHAR
This will display a list of the full path to each file that contains the search string:
foreach ($file in Get-ChildItem | Select-String -pattern "dummy" | Select-Object -Unique path) {$file.path}
Note that it doesn't display a header above the results and doesn't display the lines of text containing the search string. All it tells you is where you can find the files that contain the string.
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
The i
element is non-semantic, so for the screen readers, Googlebot, etc., it should be some kind of transparent (just like span
or div
elements). But it's not a good choice for the developer, because it joins the presentation layer with the structure layer - and that's a bad practice.
em
element (strong
as well) should be always used in a semantic context, not a presentation one. It has to be used whenever some word or sentence is important. Just for an example in the previous sentence, I should use em
to put more emphasis on the 'should be always used' part. Browsers provides some default CSS properties for these elements, but you can and you're supposed to override the default values if your design requires this to keep the correct semantic meaning of these elements.
<span class="italic">Italic Text</span>
is the most wrong way. First of all, it's inconvenient in use. Secondly, it suggest that the text should be italic. And the structure layer (HTML, XML, etc.) shouldn't ever do it. Presentation should be always kept separated from the structure.
<span class="footnote">Italic Text</span>
seems to be the best way for a footnote. It doesn't suggest any presentation and just describes the markup. You can't predict what will happen in the feature. If a footnote will grow up in the feature, you might be forced to change its class name (to keep some logic in your code).
So whenever you've some important text, use em
or strong
to emphasis it. But remember that these elements are inline elements and shouldn't be used to emphasis large blocks of text.
Use CSS if you care only about how something looks like and always try to avoid any extra markup.
You could use viewport-percentage lenghts.
See: http://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/
It works like this:
.element{
height: 100vh; /* For 100% screen height */
width: 100vw; /* For 100% screen width */
}
More info also available through Mozilla Developer Network and W3C.
I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile
or /etc/.bashrc
but otherwise, they're not permanent. They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.
You can view shell variables with the set
command (though note that unlike windows, variables are not set in linux with the set command).
set -o posix; set
(doing that set -o posix once first, helps not display too much unnecessary stuff). So set
displays shell variables.
You can view environment variables with the env
command
shell variables are set with e.g. just a = 5
environment variables are set with export, export also sets the shell variable
Here you see shell variable zzz set with zzz = 5, and see it shows when running set
but doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables
$ zzz=5
$ set | grep zzz
zzz=5
$ env | grep zzz
$ export yyy=5
$ set | grep yyy
yyy=5
$ env | grep yyy
yyy=5
$
other useful threads
https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables
https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf
then it sets $1 to asdf, and if you do echo $1
you see asdf. If you do set a=5
it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose
, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose
to turn verbose off. Windows has no such usage for its set command.
// for file with utf-8 encoding
val lines = scala.io.Source.fromFile("file.txt", "utf-8").getLines.mkString
Just add min-height:100% and min-width:100% and it will work. I had the same problem. You don't need a 3th wrapper
you really don't need quotes if let say use are using the image from your css file it can be
{background-image: url(your image.png/jpg etc);}
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
Change height using:
input[type=submit] {
border: none; /*rewriting standard style, it is necessary to be able to change the size*/
height: 100px;
width: 200px
}
Since I was especially interested in the efficiency angle, I created a little test class (below). Outcome for 5,000,000 lines:
Comparing line breaking performance of different solutions
Testing 5000000 lines
Split (all): 14665 ms
Split (CR only): 3752 ms
Scanner: 10005
Reader: 2060
As usual, exact times may vary, but the ratio holds true however often I've run it.
Conclusion: the "simpler" and "more efficient" requirements of the OP can't be satisfied simultaneously, the split
solution (in either incarnation) is simpler, but the Reader
implementation beats the others hands down.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Test class for splitting a string into lines at linebreaks
*/
public class LineBreakTest {
/** Main method: pass in desired line count as first parameter (default = 10000). */
public static void main(String[] args) {
int lineCount = args.length == 0 ? 10000 : Integer.parseInt(args[0]);
System.out.println("Comparing line breaking performance of different solutions");
System.out.printf("Testing %d lines%n", lineCount);
String text = createText(lineCount);
testSplitAllPlatforms(text);
testSplitWindowsOnly(text);
testScanner(text);
testReader(text);
}
private static void testSplitAllPlatforms(String text) {
long start = System.currentTimeMillis();
text.split("\n\r|\r");
System.out.printf("Split (regexp): %d%n", System.currentTimeMillis() - start);
}
private static void testSplitWindowsOnly(String text) {
long start = System.currentTimeMillis();
text.split("\n");
System.out.printf("Split (CR only): %d%n", System.currentTimeMillis() - start);
}
private static void testScanner(String text) {
long start = System.currentTimeMillis();
List<String> result = new ArrayList<>();
try (Scanner scanner = new Scanner(text)) {
while (scanner.hasNextLine()) {
result.add(scanner.nextLine());
}
}
System.out.printf("Scanner: %d%n", System.currentTimeMillis() - start);
}
private static void testReader(String text) {
long start = System.currentTimeMillis();
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
String line = reader.readLine();
while (line != null) {
result.add(line);
line = reader.readLine();
}
} catch (IOException exc) {
// quit
}
System.out.printf("Reader: %d%n", System.currentTimeMillis() - start);
}
private static String createText(int lineCount) {
StringBuilder result = new StringBuilder();
StringBuilder lineBuilder = new StringBuilder();
for (int i = 0; i < 20; i++) {
lineBuilder.append("word ");
}
String line = lineBuilder.toString();
for (int i = 0; i < lineCount; i++) {
result.append(line);
result.append("\n");
}
return result.toString();
}
}
-v
is the "inverted match" flag, so piping is a very good way:
grep "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)| grep -v "gloom"
import Tkinter as tk
def quit(root):
root.destroy()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()
The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.
To test this fact:
// file: test.php
sleep(10);
die("alert('Done!');");
// HTML file:
<script type="text/javascript" src="test.php"></script>
Dynamically added scripts are executed as soon as they are appended to the document.
To test this fact:
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var s = document.createElement('script');
s.type = "text/javascript";
s.src = "link.js"; // file contains alert("hello!");
document.body.appendChild(s);
alert("appended");
</script>
<script type="text/javascript">
alert("final");
</script>
</body>
</html>
Order of alerts is "appended" -> "hello!" -> "final"
If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>
) then you will get an error.
Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script>
tag and start a new one.
It's been commented multiple times that this is not the correct answer to this question, and I agree. Back when this answer was written, IE 9 was still new (about 8 months old) and many developers including myself needed a solution for <= IE 9. IE 9 is when IE started supporting background-origin
. However, it's been over six and a half years, so here's the updated solution which I highly recommend over using an actual border. In case < IE 9 support is needed. My original answer can be found below the demo snippet. It uses an opaque border to simulate padding for background images.
#hello {
padding-right: 10px;
background-color:green;
background: url("https://placehold.it/15/5C5/FFF") no-repeat scroll right center #e8e8e8;
background-origin: content-box;
}
_x000D_
<p id="hello">I want the background icon to have padding to it too!I want the background icon twant the background icon to have padding to it too!I want the background icon to have padding to it too!I want the background icon to have padding to it too!</p>
_x000D_
you can fake it with a 10px border of the same color as the background:
http://jsbin.com/eparad/edit#javascript,html,live
#hello {
border: 10px solid #e8e8e8;
background-color: green;
background: url("http://www.costascuisine.com/images/buttons/collapseIcon.gif")
no-repeat scroll right center #e8e8e8;
}
function pad(value) {
return value.tostring().padstart(2, 0);
}
let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
Try this, works for me: ls -d /a/b/c/*
The reason why folks post questions such as this is due to the dreaded- indeed "EVIL"- USB Auto-Suspend "feature".
Auto suspend winds-down the power to an "idle" USB device and unless the device's driver supports this feature correctly, the device can become uncontactable. So powering a USB port on/off is a symptom of the problem, not the problem in itself.
I'll show you how to GLOBALLY disable auto-suspend, negating the need to manually toggle the USB ports on & off:
You do NOT need to edit "autosuspend_delay_ms" individually: USB autosuspend can be disabled globally and PERSISTENTLY using the following commands:
sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&usbcore.autosuspend=-1 /' /etc/default/grub
update-grub
systemctl reboot
An Ubuntu 18.04 screen-grab follows at the end of the "Long Answer" illustrating how my results were achieved.
It's true that the USB Power Management Kernel Documentation states autosuspend is to be deprecated and in in its' place "autosuspend_delay_ms" used to disable USB autosuspend:
"In 2.6.38 the "autosuspend" file will be deprecated
and replaced by the "autosuspend_delay_ms" file."
HOWEVER my testing reveals that setting usbcore.autosuspend=-1
in /etc/default/grub as below can be used as a GLOBAL toggle for USB autosuspend functionality- you do NOT need to edit individual "autosuspend_delay_ms" files.
The same document linked above states a value of "0" is ENABLED and a negative value is DISABLED:
power/autosuspend_delay_ms
<snip> 0 means to autosuspend
as soon as the device becomes idle, and negative
values mean never to autosuspend. You can write a
number to the file to change the autosuspend
idle-delay time.
In the annotated Ubuntu 18.04 screen-grab below illustrating how my results were achieved (and reproducible), please remark the default is "0" (enabled) in autosuspend_delay_ms.
Then note that after ONLY setting usbcore.autosuspend=-1
in Grub, these values are now negative (disabled) after reboot. This will save me the bother of editing individual values and can now script disabling USB autosuspend.
Hope this makes disabling USB autosuspend a little easier and more scriptable-
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
GCM is being replaced with FCM
Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To
1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.
2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.
3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.
Here is a good question you may should have a look at it: How to add a push notification in my own android app
Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/
Essentially, and as-noted by @kevin-b:
// find('#id')
angular.element(document.querySelector('#id'))
//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))
Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).
I found the next command
mvn dependency:copy-dependencies -Dclassifier=sources
here maven.apache.org
Syntax is the structure or form of expressions, statements, and program units but Semantics is the meaning of those expressions, statements, and program units. Semantics follow directly from syntax. Syntax refers to the structure/form of the code that a specific programming language specifies but Semantics deal with the meaning assigned to the symbols, characters and words.
I did it like this.
$(document).ready(function(){
$("#yourid").click(function(){
$(this).load('@Url.Action("Details")');
});
});
Details Method:
public IActionResult Details()
{
return PartialView("Your Partial View");
}
function hasSpaces(str) {
if (str.indexOf(' ') !== -1) {
return true
} else {
return false
}
}
Unload the entire solution and then reload it again. Then Rebuild the solution. This resolved the issue for me.
Compile time recursion! :P
#include <iostream>
template<int N>
struct NumberGeneration{
static void out(std::ostream& os)
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
};
template<>
struct NumberGeneration<1>{
static void out(std::ostream& os)
{
os << 1 << std::endl;
}
};
int main(){
NumberGeneration<1000>::out(std::cout);
}
Proxy timeouts are well, for proxies, not for FastCGI...
The directives that affect FastCGI timeouts are client_header_timeout
, client_body_timeout
and send_timeout
.
Edit: Considering what's found on nginx wiki, the send_timeout directive is responsible for setting general timeout of response (which was bit misleading). For FastCGI there's fastcgi_read_timeout
which is affecting the fastcgi process response timeout.
HTH.
Even I faced the same issue, later I found that it happened because the maven build operation was not happening properly in my environment. Please check it in your case also.
Wow, there are some complex solutions here. So complex I decided to come up with something simpler but also quite powerful. Here it is;
function sortByPriority(data, priorities) {
if (priorities.length == 0) {
return data;
}
const nextPriority = priorities[0];
const remainingPriorities = priorities.slice(1);
const matched = data.filter(item => item.hasOwnProperty(nextPriority));
const remainingData = data.filter(item => !item.hasOwnProperty(nextPriority));
return sortByPriority(matched, remainingPriorities)
.sort((a, b) => (a[nextPriority] > b[nextPriority]) ? 1 : -1)
.concat(sortByPriority(remainingData, remainingPriorities));
}
And here is an example of how you use it.
const data = [
{ id: 1, mediumPriority: 'bbb', lowestPriority: 'ggg' },
{ id: 2, highestPriority: 'bbb', mediumPriority: 'ccc', lowestPriority: 'ggg' },
{ id: 3, mediumPriority: 'aaa', lowestPriority: 'ggg' },
];
const priorities = [
'highestPriority',
'mediumPriority',
'lowestPriority'
];
const sorted = sortByPriority(data, priorities);
This will first sort by the precedence of the attributes, then by the value of the attributes.
To hopefully make all of this a little more concrete, here’s a worked example of configuring a Spark app to use as much of the cluster as possible: Imagine a cluster with six nodes running NodeManagers, each equipped with 16 cores and 64GB of memory. The NodeManager capacities, yarn.nodemanager.resource.memory-mb and yarn.nodemanager.resource.cpu-vcores, should probably be set to 63 * 1024 = 64512 (megabytes) and 15 respectively. We avoid allocating 100% of the resources to YARN containers because the node needs some resources to run the OS and Hadoop daemons. In this case, we leave a gigabyte and a core for these system processes. Cloudera Manager helps by accounting for these and configuring these YARN properties automatically.
The likely first impulse would be to use --num-executors 6 --executor-cores 15 --executor-memory 63G. However, this is the wrong approach because:
63GB + the executor memory overhead won’t fit within the 63GB capacity of the NodeManagers. The application master will take up a core on one of the nodes, meaning that there won’t be room for a 15-core executor on that node. 15 cores per executor can lead to bad HDFS I/O throughput.
A better option would be to use --num-executors 17 --executor-cores 5 --executor-memory 19G. Why?
This config results in three executors on all nodes except for the one with the AM, which will have two executors. --executor-memory was derived as (63/3 executors per node) = 21. 21 * 0.07 = 1.47. 21 – 1.47 ~ 19.
The explanation was given in an article in Cloudera's blog, How-to: Tune Your Apache Spark Jobs (Part 2).
There are many methods to do this using constraint widget of the activity.xml page of android studio.
Two most common methods are:
You probably want the next transformation for you pixels:
pixels = map(list, image.getdata())
You can use the following code to add column to Datatable at postion 0:
DataColumn Col = datatable.Columns.Add("Column Name", System.Type.GetType("System.Boolean"));
Col.SetOrdinal(0);// to put the column in position 0;
DECLARE @EmpGroup INT =3 ,
@IsActive BIT=1
DECLARE @tblEmpMaster AS TABLE
(EmpCode VARCHAR(20),EmpName VARCHAR(50),EmpAddress VARCHAR(500))
INSERT INTO @tblEmpMaster EXECUTE SPGetEmpList @EmpGroup,@IsActive
SELECT * FROM @tblEmpMaster
Here's a little trick I'm using lately and brings good results. I would like to share with those who have to fight often with VBA.
1.- Implement a public initiation subroutine in each of your custom classes. I call it InitiateProperties throughout all my classes. This method has to accept the arguments you would like to send to the constructor.
2.- Create a module called factory, and create a public function with the word "Create" plus the same name as the class, and the same incoming arguments as the constructor needs. This function has to instantiate your class, and call the initiation subroutine explained in point (1), passing the received arguments. Finally returned the instantiated and initiated method.
Example:
Let's say we have the custom class Employee. As the previous example, is has to be instantiated with name and age.
This is the InitiateProperties method. m_name and m_age are our private properties to be set.
Public Sub InitiateProperties(name as String, age as Integer)
m_name = name
m_age = age
End Sub
And now in the factory module:
Public Function CreateEmployee(name as String, age as Integer) as Employee
Dim employee_obj As Employee
Set employee_obj = new Employee
employee_obj.InitiateProperties name:=name, age:=age
set CreateEmployee = employee_obj
End Function
And finally when you want to instantiate an employee
Dim this_employee as Employee
Set this_employee = factory.CreateEmployee(name:="Johnny", age:=89)
Especially useful when you have several classes. Just place a function for each in the module factory and instantiate just by calling factory.CreateClassA(arguments), factory.CreateClassB(other_arguments), etc.
As stenci pointed out, you can do the same thing with a terser syntax by avoiding to create a local variable in the constructor functions. For instance the CreateEmployee function could be written like this:
Public Function CreateEmployee(name as String, age as Integer) as Employee
Set CreateEmployee = new Employee
CreateEmployee.InitiateProperties name:=name, age:=age
End Function
Which is nicer.
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
What is the reason for the try-except-else to exist?
A try
block allows you to handle an expected error. The except
block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs.
An else
clause will execute if there were no errors, and by not executing that code in the try
block, you avoid catching an unexpected error. Again, catching an unexpected error can hide bugs.
For example:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
else:
return something
The "try, except" suite has two optional clauses, else
and finally
. So it's actually try-except-else-finally
.
else
will evaluate only if there is no exception from the try
block. It allows us to simplify the more complicated code below:
no_error = None
try:
try_this(whatever)
no_error = True
except SomeException as the_exception:
handle(the_exception)
if no_error:
return something
so if we compare an else
to the alternative (which might create bugs) we see that it reduces the lines of code and we can have a more readable, maintainable, and less buggy code-base.
finally
finally
will execute no matter what, even if another line is being evaluated with a return statement.
It might help to break this down, in the smallest possible form that demonstrates all features, with comments. Assume this syntactically correct (but not runnable unless the names are defined) pseudo-code is in a function.
For example:
try:
try_this(whatever)
except SomeException as the_exception:
handle_SomeException(the_exception)
# Handle a instance of SomeException or a subclass of it.
except Exception as the_exception:
generic_handle(the_exception)
# Handle any other exception that inherits from Exception
# - doesn't include GeneratorExit, KeyboardInterrupt, SystemExit
# Avoid bare `except:`
else: # there was no exception whatsoever
return something()
# if no exception, the "something()" gets evaluated,
# but the return will not be executed due to the return in the
# finally block below.
finally:
# this block will execute no matter what, even if no exception,
# after "something" is eval'd but before that value is returned
# but even if there is an exception.
# a return here will hijack the return functionality. e.g.:
return True # hijacks the return in the else clause above
It is true that we could include the code in the else
block in the try
block instead, where it would run if there were no exceptions, but what if that code itself raises an exception of the kind we're catching? Leaving it in the try
block would hide that bug.
We want to minimize lines of code in the try
block to avoid catching exceptions we did not expect, under the principle that if our code fails, we want it to fail loudly. This is a best practice.
It is my understanding that exceptions are not errors
In Python, most exceptions are errors.
We can view the exception hierarchy by using pydoc. For example, in Python 2:
$ python -m pydoc exceptions
or Python 3:
$ python -m pydoc builtins
Will give us the hierarchy. We can see that most kinds of Exception
are errors, although Python uses some of them for things like ending for
loops (StopIteration
). This is Python 3's hierarchy:
BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
ModuleNotFoundError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
RecursionError
StopAsyncIteration
StopIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
A commenter asked:
Say you have a method which pings an external API and you want to handle the exception at a class outside the API wrapper, do you simply return e from the method under the except clause where e is the exception object?
No, you don't return the exception, just reraise it with a bare raise
to preserve the stacktrace.
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
raise
Or, in Python 3, you can raise a new exception and preserve the backtrace with exception chaining:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
raise DifferentException from the_exception
I elaborate in my answer here.
Here's a quick solution for this. Say, you have a data frame X with three columns A, B and C:
> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6))
> X
A B C
1 1 3 5
2 2 4 6
If I want to remove a column, say B, just use grep on colnames to get the column index, which you can then use to omit the column.
> X<-X[,-grep("B",colnames(X))]
Your new X data frame would look like the following (this time without the B column):
> X
A C
1 1 5
2 2 6
The beauty of grep is that you can specify multiple columns that match the regular expression. If I had X with five columns (A,B,C,D,E):
> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,8),E=c(9,10))
> X
A B C D E
1 1 3 5 7 9
2 2 4 6 8 10
Take out columns B and D:
> X<-X[,-grep("B|D",colnames(X))]
> X
A C E
1 1 5 9
2 2 6 10
EDIT: Considering the grepl suggestion of Matthew Lundberg in the comments below:
> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,8),E=c(9,10))
> X
A B C D E
1 1 3 5 7 9
2 2 4 6 8 10
> X<-X[,!grepl("B|D",colnames(X))]
> X
A C E
1 1 5 9
2 2 6 10
If I try to drop a column that's non-existent,nothing should happen:
> X<-X[,!grepl("G",colnames(X))]
> X
A C E
1 1 5 9
2 2 6 10
ax.axis('off')
, will as Joe Kington pointed out, remove everything except the plotted line.
For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the spines
object on the axis. Given an axis object ax
, the following should remove borders on all four sides:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
And, in case of removing x
and y
ticks from the plot:
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
Also, name it divrat.m
, not divrat.M
. This shouldn't matter on most OSes, but who knows...
You can also test whether matlab can find a function by using the which
command, i.e.
which divrat
You can use my highlight
script from https://github.com/kepkin/dev-shell-essentials
It's better than grep
because you can highlight each match with its own color.
$ command_here | highlight green "input" | highlight red "output"
If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:
library ieee;
use ieee.std_logic_1164.all;
entity tb is
end entity;
architecture sim of tb is
-- Procedure for clock generation
procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
constant PERIOD : time := 1 sec / FREQ; -- Full period
constant HIGH_TIME : time := PERIOD / 2; -- High time
constant LOW_TIME : time := PERIOD - HIGH_TIME; -- Low time; always >= HIGH_TIME
begin
-- Check the arguments
assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
-- Generate a clock cycle
loop
clk <= '1';
wait for HIGH_TIME;
clk <= '0';
wait for LOW_TIME;
end loop;
end procedure;
-- Clock frequency and signal
signal clk_166 : std_logic;
signal clk_125 : std_logic;
begin
-- Clock generation with concurrent procedure call
clk_gen(clk_166, 166.667E6); -- 166.667 MHz clock
clk_gen(clk_125, 125.000E6); -- 125.000 MHz clock
-- Time resolution show
assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;
end architecture;
The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.
If the clk_gen
procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.
Waveform for clocks are shown in figure below.
An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:
-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
constant HIGH_TIME : time := 0.5 sec / FREQ; -- High time as fixed value
variable low_time_v : time; -- Low time calculated per cycle; always >= HIGH_TIME
variable cycles_v : real := 0.0; -- Number of cycles
variable freq_time_v : time := 0 fs; -- Time used for generation of cycles
begin
-- Check the arguments
assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
-- Initial phase shift
clk <= '0';
wait for PHASE;
-- Generate cycles
loop
-- Only high pulse if run is '1' or 'H'
if (run = '1') or (run = 'H') then
clk <= run;
end if;
wait for HIGH_TIME;
-- Low part of cycle
clk <= '0';
low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME; -- + 1.0 for cycle after current
wait for low_time_v;
-- Cycle counter and time passed update
cycles_v := cycles_v + 1.0;
freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
end loop;
end procedure;
Again reuse through a package will be nice.
Come on guys :) We could do it simpler, by examples:
/this-is-an-endpoint
/another/endpoint
/some/other/endpoint
/login
/accounts
/cart/items
and when put under a domain, it would look like:
https://example.com/this-is-an-endpoint
https://example.com/another/endpoint
https://example.com/some/other/endpoint
https://example.com/login
https://example.com/accounts
https://example.com/cart/items
Can be either http or https, we use https in the example.
Also endpoint can be different for different HTTP methods, for example:
GET /item/{id}
PUT /item/{id}
would be two different endpoints - one for retrieving (as in "cRud" abbreviation), and the other for updating (as in "crUd")
And that's all, really that simple!
$("#form-field").val("5").trigger("change");
To animate your 3D object, use the code:
<script>
$(document).ready(function(){
var x = 100;
var y = 0;
setInterval(function(){
x += 1;
y += 1;
var element = document.getElementById('cube');
element.style.webkitTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome
element.style.MozTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
},50);
//for other browsers use: "msTransform", "OTransform", "transform"
});
</script>
select u from UserGroup ug inner join ug.user u
where ug.group_id = :groupId
order by u.lastname
As a named query:
@NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.
Changing the background property might not be enough as the component won't look like a button anymore. You might need to re-implement the paint method as in here to get a better result:
I was beginning to go mad while searching for the real configuration, so here is the list of all configuration files on linux:
on windows:
Then in this file the prefix is configured:
prefix=/usr
The prefix is defaulted to /usr in linux, to ${APPDATA}\npm in windows
The node modules are under $prefix tree, and the path should contain $prefix/bin
There may be a problem :
/root/.npmrc
may be used!/home/youruser/.npmrc
.npm set -g prefix /usr
it sets the /etc/npmrc global, but doesn't override the localHere is all the informations that were missing to find what is configured where. Hope I have been exhaustive.
I had similar issue. try this $('#myAnchor').get(0).click();
this works for me
Env: macOS Mojave 10.14.4
Install: homebrew
Location:/usr/local/Cellar/mongodb/4.0.3_1
Note :If update version by
brew upgrade mongo
,the folder 4.0.4_1
will be removed and replace with the new version folder
This happens when a python extension (written in C) tries to access a memory beyond reach.
You can trace it in following ways.
sys.settrace
at the very first line of the code.Use gdb
as described by Mark in this answer.. At the command prompt
gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code
You first need to create a table in your database in which you will be importing the CSV file. After the table is created, follow the steps below.
• Log into your database using SQL Server Management Studio
• Right click on your database and select Tasks -> Import Data...
• Click the Next >
button
• For the Data Source, select Flat File Source
. Then use the Browse button to select the CSV file. Spend some time configuring how you want the data to be imported before clicking on the Next >
button.
• For the Destination, select the correct database provider (e.g. for SQL Server 2012, you can use SQL Server Native Client 11.0). Enter the Server name. Check the Use SQL Server Authentication
radio button. Enter the User name, Password, and Database before clicking on the Next >
button.
• On the Select Source Tables and Views window, you can Edit Mappings before clicking on the Next >
button.
• Check the Run immediately
check box and click on the Next >
button.
• Click on the Finish
button to run the package.
The above was found on this website (I have used it and tested):
set -x
will give you what you want.
Here is an example shell script to demonstrate:
#!/bin/bash
set -x #echo on
ls $PWD
This expands all variables and prints the full commands before output of the command.
Output:
+ ls /home/user/
file1.txt file2.txt
This is also fine:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
}
public class FragmentTab1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
return rootView;
}
}
class MyPagerAdapter extends FragmentPagerAdapter{
public MyPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
switch(position){
case 0:
FragmentTab1 fm = new FragmentTab1();
return fm;
case 1: return new FragmentTab2();
case 2: return new FragmentTab3();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/Fragment1" />
</RelativeLayout>
You can easily import your model and run this:
from models import User
# User is the name of table that has a column name
users = User.query.all()
for user in users:
print user.name
In Laravel use Carbon its good
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
private String getCurrentStackTraceString() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
return Arrays.stream(stackTrace).map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
}
Maybe you can take a look at closure in JavaScript. Here is a working solution:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<p class="button">Button 0</p>_x000D_
<p class="button">Button 1</p>_x000D_
<p class="button">Button 2</p>_x000D_
<script>_x000D_
var buttons = document.getElementsByClassName('button');_x000D_
for (var i=0 ; i < buttons.length ; i++){_x000D_
(function(index){_x000D_
buttons[index].onclick = function(){_x000D_
alert("I am button " + index);_x000D_
};_x000D_
})(i)_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of
$ git lola * 2582152 (HEAD, master) Merge branch 'otherguy' |\ | * c7256de (otherguy) bar * | b7e7176 baz |/ * 9968f79 foo
Note: git lola is a non-standard but useful alias.
No dice with git revert
:
$ git revert HEAD fatal: Commit 2582152... is a merge but no -m option was given.
Charles Bailey gave an excellent answer as usual. Using git revert
as in
$ git revert --no-edit -m 1 HEAD [master e900aad] Revert "Merge branch 'otherguy'" 0 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 bar
effectively deletes bar
and produces a history of
$ git lola * e900aad (HEAD, master) Revert "Merge branch 'otherguy'" * 2582152 Merge branch 'otherguy' |\ | * c7256de (otherguy) bar * | b7e7176 baz |/ * 9968f79 foo
But I suspect you want to throw away the merge commit:
$ git reset --hard HEAD^ HEAD is now at b7e7176 baz $ git lola * b7e7176 (HEAD, master) baz | * c7256de (otherguy) bar |/ * 9968f79 foo
As documented in the git rev-parse
manual
<rev>^
, e.g. HEAD^,v1.5.1^0
A suffix^
to a revision parameter means the first parent of that commit object.^<n>
means the n-th parent (i.e.<rev>^
is equivalent to<rev>^1
). As a special rule,<rev>^0
means the commit itself and is used when<rev>
is the object name of a tag object that refers to a commit object.
so before invoking git reset
, HEAD^
(or HEAD^1
) was b7e7176 and HEAD^2
was c7256de, i.e., respectively the first and second parents of the merge commit.
Be careful with git reset --hard
because it can destroy work.
we can use javascript code
function validateAlphaNumericCode(event) {
keyEntry = (event.which) ? event.which : event.keyCode
if (((keyEntry >= '65') && (keyEntry <= '90')) || ((keyEntry >= '97') && (keyEntry <= '122')) || (keyEntry == '37') || (keyEntry == '39') || (keyEntry == '46') || (keyEntry == '8') || (keyEntry == '9') || (keyEntry == '95') || ((keyEntry >= '48') && (keyEntry <= '57')))
return true;
else
return false;
}
validate this code with your textbox.
I have a partial solution that I came up with. It uses a regular expression to extract the month and day name. But as I look through the Region and Language options (Windows) I realize that different cultures have different format order... maybe a better regular expression pattern could be useful.
function testDateInfo() {
var months = new Array();
var days = new Array();
var workingDate = new Date();
workingDate.setHours(0, 0, 0, 0);
workingDate.setDate(1);
var RE = new RegExp("([a-z]+)","ig");
//-- get day names 0-6
for (var i = 0; i < 7; i++) {
var day = workingDate.getDay();
//-- will eventually be in order
if (days[day] == undefined)
days[day] = workingDate.toLocaleDateString().match(RE)[0];
workingDate.setDate(workingDate.getDate() + 1);
}
//--get month names 0-11
for (var i = 0; i < 12; i++) {
workingDate.setMonth(i);
months.push(workingDate.toLocaleDateString().match(RE)[1]);
}
alert(days.join(",") + " \n\r " + months.join(","));
}
The problem with GCM is that there is a lot of configuration involved in the process:
If you like simple things (like me) you should try UrbanAirship. It is (IMHO) the easiest way to use GCM in your app without doing a lot of configuration. It also gives you a pretty GUI to test that your GCM messages are being delivered correctly.
Note: I am not afiliated with UrbanAirship in any way
For all kind of files, subdirectories included:
import os
list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files
Only files (avoiding subdirectories):
import os
onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)
python script_name.py > saveit.txt
Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies. For instance, By this, we can route the printed output of a Python script to a file to save it.
I have also face the Auth Fail issue, the problem with my code is that I have
channelSftp.cd("");
It changed it to
channelSftp.cd(".");
Then it works.
In bash, use $OSTYPE
and $HOSTTYPE
, as documented; this is what I do. If that is not enough, and if even uname
or uname -a
(or other appropriate options) does not give enough information, there’s always the config.guess script from the GNU project, made exactly for this purpose.
It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:
public isEmpty(myVar): boolean {
return (myVar && (Object.keys(myVar).length === 0));
}
Otherwise: if (!myVar) {}, should do the job
You must have the pyserial library installed. You do not need the serial library.Therefore, if the serial library is pre-installed, uninstall it. Install the pyserial libray. There are many methods of installing:-
pip install pyserial
pip install <wheelname>
Link: https://github.com/pyserial/pyserial/releases
After installing Pyserial, Navigate to the location where pyserial is installed. You will see a "setup.py" file. Open Power Shell or CMD in the same directory and run command "python setup.py install
".
Now you can use all functionalities of pyserial library without any error.
Why do you care?
99.99% of the time, you shouldn't care.
These sorts of micro-optimizations are unlikely to affect the performance of your code.
Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.
Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
I am a very good iPhone app developer, and I charge over $150 per hour for my services. I have a ton of experience building iPhone apps and their server side components. I have also been called in on several occasions to fix offshore developed apps. Here's my take.
I'm just about to release a shopping app for a client. The design work was done by 2 client in-house designers over 2 weeks, quick because they had all the image assets already. Think 2 people x 10 days x 8 hours = ~$24,000. The server side had to be modified to provide data for the iPhone app. We used their in-house team and in-house platform and in-house API, 2 developers, 4 weeks, or about $50,000 and that's because they already have a web shop and API. Cost them about $400,000 to get there (excluding platform). And I wrote the app side in 3 weeks, given that a lot of my code is duplicated from previous projects, another ~$25,000, the cheapest app I ever did.
Total spent: ~$100,000, and that's insanely cheap!
And they will give this away for free so clients will buy from their store from their iPhones.
For your app, Peter, if you have the servers and the APIs and the design, I'd guess at $30,000 to $60,000 depending on complexity. If you do not have the design, double it. If you do not have the APIs, double again...
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
Accidently I found a simple workaroud to this issue. Running Maven with -X option forces it to try other servers to download source code. Instead of trash HTML inside some jar files there is correct content.
mvn clean install -X > d:\log.txt
And in the log file you find messages like these:
Downloading: https://repository.apache.org/content/groups/public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar
[DEBUG] Writing resolution tracking file D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar.lastUpdated
Downloading: http://maven.wso2.org/nexus/content/groups/wso2-public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar
You see, Maven switched repository.apache.org to maven.wso2.org when it encountered a download problem. So the following error is now gone:
[ERROR] error: error reading D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar; error in opening zip file
This error message can be thrown in the application logs when the actual issue is that the oracle database server ran out of space.
After correcting the space issue, this particular error message disappeared.
Instead of a size divisor of 1024 * 1024
you could use the <<
bitwise shifting operator, i.e. 1<<20
to get megabytes, 1<<30
to get gigabytes, etc.
In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20)
which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR
.
Megabytes are usually all that you need, or otherwise something like this can be used:
# bytes pretty-printing
UNITS_MAPPING = [
(1<<50, ' PB'),
(1<<40, ' TB'),
(1<<30, ' GB'),
(1<<20, ' MB'),
(1<<10, ' KB'),
(1, (' byte', ' bytes')),
]
def pretty_size(bytes, units=UNITS_MAPPING):
"""Get human-readable file sizes.
simplified version of https://pypi.python.org/pypi/hurry.filesize/
"""
for factor, suffix in units:
if bytes >= factor:
break
amount = int(bytes / factor)
if isinstance(suffix, tuple):
singular, multiple = suffix
if amount == 1:
suffix = singular
else:
suffix = multiple
return str(amount) + suffix
print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))
## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB
No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.
In other words, your code only works by accident, and probably not in all browsers.
Is this what you're trying to do?
<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
This is how I was able to configure yaml files to refer to variable.
I have values.yaml
where we have root level fields which are used as template variables inside values.yaml
values.yaml
.....
databaseUserPropName: spring.datasource.username
databaseUserName: sa
.....
secrets:
type: Opaque
name: dbservice-secrets
data:
- name: "{{ .Values.databaseUserPropName }}"
value: "{{ .Values.databaseUserName }}"
.....
When referencing these values in secret.yaml
, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}
secret.yaml
when using inside range i:e iteration
{{ range .Values.deployments.secrets.data }}
{{ tpl .name $ }}: "{{ tpl .value $ }}"
{{ end }}
when directly referring as variable
{{ tpl .Values.deployments.secrets.data.name . }}
{{ tpl .Values.deployments.secrets.data.value . }}
$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.
For those using Cygwin 1.7.34 or higher Cygwin supports configuring how to fetch home directory, login shell, and gecos information in /etc/nsswitch.conf
. This is detailed in the Cygwin User Guide section:
If you've previously created an /etc/passwd
or /etc/group
file you'll want to remove those and configure Cygwin using the new Windows Security model to POSIX mappings.
[[ -f /etc/passwd ]] && mv /etc/passwd /etc/passwd.bak
[[ -f /etc/group ]] && mv /etc/group /etc/group.bak
The /etc/nsswitch.conf
file's db_home:
setting defines how Cygwin fetches the user's home directory. The default setting for db_home:
is
db_home: /home/%U
So by default, Cygwin just sets the home dir to /home/$USERNAME
. You can change that though to point at any other custom path you want. The supported wildcard characters are:
%u
The Cygwin username (that's lowercase u).%U
The Windows username (that's uppercase U).%D
Windows domain in NetBIOS style.%H
Windows home directory in POSIX style. Note that, for the db_home:
setting, this only makes sense right after the preceeding slash, as in db_home: /%H/cygwin
%_
Since space and TAB characters are used to separate the schemata, a space in the filename has to be given as %_
(that's an underscore).%%
A per-cent character.In place of a path, you can specify one of four named path schemata that are predefined.
windows
The user's home directory is set to the same directory which is used as Windows home directory, typically something along the lines of %USERPROFILE%
or C:\Users\$USERNAME
. Of course, the Windows directory is converted to POSIX-style by Cygwin.
cygwin
AD only: The user's home directory is set to the POSIX path given in the cygwinHome attribute from the cygwinUser auxiliary class. See also the section called “The cygwin schema”.
unix
AD only: The user's home directory is set to the POSIX path given in the unixHomeDirectory attribute from the posixAccount auxiliary class. See also the section called “The unix schema”.
desc
The user's home directory is set to the POSIX path given in the home="..." XML-alike setting in the user's description attribute in SAM or AD. See the section called “The desc schema” for a detailed description.
The following will make the user's home directory in Cygwin the same as is used for the Windows home directory.
db_home: windows
For those using Cygwin 1.7.33 or earlier, update to the latest version Cygwin and remove previously used /etc/passwd
and /etc/group
files, then see the steps above.
Else, follow these older steps below.
Firstly, set a Windows environment variable for HOME that points to your user profile:
HOME
%USERPROFILE%
Now we are going to update the Cygwin /etc/passwd
file with the Windows %HOME%
variable we just created. Shell logins and remote logins via ssh
will rely on /etc/passwd
to tell them the location of the user's $HOME
path.
At the Cygwin bash command prompt type the following:
cp /etc/passwd /etc/passwd.bak
mkpasswd -l -p $(cygpath -H) > /etc/passwd
mkpasswd -d -p $(cygpath -H) >> /etc/passwd
The -d
switch tells mkpasswd to include DOMAIN users, while -l
is to only output LOCAL machine users. This is important if you're using a PC at work where the user information is obtained from a Windows Domain Controller.
Now, you can also do the same for groups, though this is not necessary unless you will be using a computer that is part of a Windows Domain. Cygwin reads group information from the Windows account databases, but you can add an /etc/group
file if your machine is often disconnected from its Domain Controller.
At the Cygwin bash prompt type the following:
cp /etc/group /etc/group.bak
mkgroup -l > /etc/group
mkgroup -d >> /etc/group
Now, exit Cygwin and start it up again. You should find that your HOME path points to the same location as your Windows User Profile -- i.e. /cygdrive/c/Users/username
You are performing calculations on integers and assigning its result to float. So compiler is implicitly converting your integer result into float
I doubt if any of those should work. Try: First import the namespace in the beginning of the code page as below.
using System.Drawing;
then in the code.
Button4.BackColor = Color.LawnGreen;
Hope it helps.
You CAN do this with gradle. I've made a demo project showing how.
The trick is to use gradle's ability to merge multiple resource folders, and set the res folder as well as the nested subfolders in the sourceSets block.
The quirk is that you can't declare a container resource folder before you declare that folder's child resource folders.
Below is the sourceSets block from the build.gradle file from the demo. Notice that the subfolders are declared first.
sourceSets {
main {
res.srcDirs =
[
'src/main/res/layouts/layouts_category2',
'src/main/res/layouts',
'src/main/res'
]
}
}
Also, the direct parent of your actual resource files (pngs, xml layouts, etc..) does still need to correspond with the specification.
You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).
For instance :
System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK // API Level
android.os.Build.DEVICE // Device
android.os.Build.MODEL // Model
android.os.Build.PRODUCT // Product
Etc...
let us see the below source code. Here fragment name is DirectoryOfEbooks. After completion of the background task, i am the replacing the frame with current fragment. so the fragment gets refreshed and reloads its data
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.data.LineRadarDataSet;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class DirectoryOfEbooks extends Fragment {
RecyclerView recyclerView;
branchesAdapter adapter;
LinearLayoutManager linearLayoutManager;
Cursor c;
FragmentTransaction fragmentTransaction;
SQLiteDatabase db;
List<branch_sync> directoryarraylist;
public DirectoryOfEbooks() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_directory_of_ebooks, container, false);
directoryarraylist = new ArrayList<>();
db = getActivity().openOrCreateDatabase("notify", android.content.Context.MODE_PRIVATE, null);
c = db.rawQuery("select * FROM branch; ", null);
if (c.getCount() != 0) {
c.moveToFirst();
while (true) {
//String ISBN = c.getString(c.getColumnIndex("ISBN"));
String branch = c.getString(c.getColumnIndex("branch"));
branch_sync branchSync = new branch_sync(branch);
directoryarraylist.add(branchSync);
if (c.isLast())
break;
else
c.moveToNext();
}
recyclerView = (RecyclerView) view.findViewById(R.id.directoryOfEbooks);
adapter = new branchesAdapter(directoryarraylist, this.getContext());
adapter.setHasStableIds(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
System.out.println("ebooks");
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this.getContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
System.out.println(adapter.getItemCount()+"adpater count");
}
// Inflate the layout for this fragment
return view;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.fragment_books);
setHasOptionsMenu(true);
}
public void onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.refresh, menu);
MenuItem menuItem = menu.findItem(R.id.refresh1);
menuItem.setVisible(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.refresh1) {
new AlertDialog.Builder(getContext()).setMessage("Refresh takes more than a Minute").setPositiveButton("Refresh Now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new refreshebooks().execute();
}
}).setNegativeButton("Refresh Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).setCancelable(false).show();
}
return super.onOptionsItemSelected(item);
}
public class refreshebooks extends AsyncTask<String,String,String>{
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(getContext());
progressDialog.setMessage("\tRefreshing Ebooks .....");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
Ebooksync syncEbooks=new Ebooksync();
String status=syncEbooks.syncdata(getContext());
return status;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("error")){
progressDialog.dismiss();
Toast.makeText(getContext(),"Refresh Failed",Toast.LENGTH_SHORT).show();
}
else{
fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mainframe, new DirectoryOfEbooks());
fragmentTransaction.commit();
progressDialog.dismiss();
adapter.notifyDataSetChanged();
Toast.makeText(getContext(),"Refresh Successfull",Toast.LENGTH_SHORT).show();
}
}
}
}
In the Solution Explorer window, right click the project you want to use your class library from and click the 'Add Reference' menu item. Then if the class library is in the same solution file, go to the projects tab and select it; if it's not in the same tab, you can go to the Browse tab and find it that way.
Then you can use anything in that assembly.
If you want to capitalize every first letter in a string, for example hello to the world
becomes Hello To The World
you can use the following (repurposed from Steve Harrison):
function capitalizeEveryFirstLetter(string) {
var splitStr = string.split(' ')
var fullStr = '';
$.each(splitStr,function(index){
var currentSplit = splitStr[index].charAt(0).toUpperCase() + splitStr[index].slice(1);
fullStr += currentSplit + " "
});
return fullStr;
}
Which you can call by using the following:
capitalizeFirstLetter("hello to the world");
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript()
function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment
link multiple times, tinymce.js
will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript()
documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript()
function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup()
as follows:
$.ajaxSetup({
cache: true
});
using(var tw = new StreamWriter(path, File.Exists(path)))
{
tw.WriteLine(message);
}
public static async Task<byte[]> GetBytesAsync(string url) {
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = await request.GetResponseAsync())
using (var content = new MemoryStream())
using (var responseStream = response.GetResponseStream()) {
await responseStream.CopyToAsync(content);
return content.ToArray();
}
}
public static async Task<string> GetStringAsync(string url) {
var bytes = await GetBytesAsync(url);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
Just define your variables in global.js outside a function scope:
// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";
// other js-file
function testGlobal () {
alert(global1);
}
To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:
<html>
<head>
<!-- Include global.js first -->
<script src="/YOUR_PATH/global.js" type="text/javascript"></script>
<!-- Now we can reference variables, objects, functions etc.
defined in global.js -->
<script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
</head>
[...]
</html>
You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.
Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.
<svg style='stroke-width: 0px; background-color: blue;'> </svg>
Try this :
SELECT
(
SELECT
`NAME`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) as `NAME`
FROM
school_locations
WHERE
(
SELECT
`TYPE`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) = 'coun';
I was able to exclude the jquery.mobile 1.1.1 in Juno by selecting Add Multiple next to the Exlusion Patterns, which brings up the tree, then drilling down to the jquery-mobile folder and selecting that.
This corrected all the warnings for the library!
Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
UPDATE for API 26 to set Max priority
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
As offer_date
is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date
SELECT
*
FROM
offers
WHERE
offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0
Also, by doing all the manipulation on the create_date
you only do the processing on one value.
Additionally, had you manipulated the offer_date
you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
After rigorous searching i finally settled with the following
^[a-zA-Z0-9]+\:\/\/[a-zA-Z0-9]+\.[-a-zA-Z0-9]+\.?[a-zA-Z0-9]+$|^[a-zA-Z0-9]+\.[-a-zA-Z0-9]+\.[a-zA-Z0-9]+$
And this thing work for general in future URLs.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
You can achieve this by controlling the formatting of the old/new/unchanged lines in GNU diff
output:
diff --new-line-format="" --unchanged-line-format="" file1 file2
The input files should be sorted for this to work. With bash
(and zsh
) you can sort in-place with process substitution <( )
:
diff --new-line-format="" --unchanged-line-format="" <(sort file1) <(sort file2)
In the above new and unchanged lines are suppressed, so only changed (i.e. removed lines in your case) are output. You may also use a few diff
options that other solutions don't offer, such as -i
to ignore case, or various whitespace options (-E
, -b
, -v
etc) for less strict matching.
Explanation
The options --new-line-format
, --old-line-format
and --unchanged-line-format
let you control the way diff
formats the differences, similar to printf
format specifiers. These options format new (added), old (removed) and unchanged lines respectively. Setting one to empty "" prevents output of that kind of line.
If you are familiar with unified diff format, you can partly recreate it with:
diff --old-line-format="-%L" --unchanged-line-format=" %L" \
--new-line-format="+%L" file1 file2
The %L
specifier is the line in question, and we prefix each with "+" "-" or " ", like diff -u
(note that it only outputs differences, it lacks the ---
+++
and @@
lines at the top of each grouped change).
You can also use this to do other useful things like number each line with %dn
.
The diff
method (along with other suggestions comm
and join
) only produce the expected output with sorted input, though you can use <(sort ...)
to sort in place. Here's a simple awk
(nawk) script (inspired by the scripts linked-to in Konsolebox's answer) which accepts arbitrarily ordered input files, and outputs the missing lines in the order they occur in file1.
# output lines in file1 that are not in file2
BEGIN { FS="" } # preserve whitespace
(NR==FNR) { ll1[FNR]=$0; nl1=FNR; } # file1, index by lineno
(NR!=FNR) { ss2[$0]++; } # file2, index by string
END {
for (ll=1; ll<=nl1; ll++) if (!(ll1[ll] in ss2)) print ll1[ll]
}
This stores the entire contents of file1 line by line in a line-number indexed array ll1[]
, and the entire contents of file2 line by line in a line-content indexed associative array ss2[]
. After both files are read, iterate over ll1
and use the in
operator to determine if the line in file1 is present in file2. (This will have have different output to the diff
method if there are duplicates.)
In the event that the files are sufficiently large that storing them both causes a memory problem, you can trade CPU for memory by storing only file1 and deleting matches along the way as file2 is read.
BEGIN { FS="" }
(NR==FNR) { # file1, index by lineno and string
ll1[FNR]=$0; ss1[$0]=FNR; nl1=FNR;
}
(NR!=FNR) { # file2
if ($0 in ss1) { delete ll1[ss1[$0]]; delete ss1[$0]; }
}
END {
for (ll=1; ll<=nl1; ll++) if (ll in ll1) print ll1[ll]
}
The above stores the entire contents of file1 in two arrays, one indexed by line number ll1[]
, one indexed by line content ss1[]
. Then as file2 is read, each matching line is deleted from ll1[]
and ss1[]
. At the end the remaining lines from file1 are output, preserving the original order.
In this case, with the problem as stated, you can also divide and conquer using GNU split
(filtering is a GNU extension), repeated runs with chunks of file1 and reading file2 completely each time:
split -l 20000 --filter='gawk -f linesnotin.awk - file2' < file1
Note the use and placement of -
meaning stdin
on the gawk
command line. This is provided by split
from file1 in chunks of 20000 line per-invocation.
For users on non-GNU systems, there is almost certainly a GNU coreutils package you can obtain, including on OSX as part of the Apple Xcode tools which provides GNU diff
, awk
, though only a POSIX/BSD split
rather than a GNU version.
You can use
moment().isSameOrBefore(Moment|String|Number|Date|Array);
moment().isSameOrAfter(Moment|String|Number|Date|Array);
or
moment().isBetween(moment-like, moment-like);
See here : http://momentjs.com/docs/#/query/
You can also set auto completion to open automatically while typing.
Go to Preferences
> Java
> Editor
> Content Assist
and write .abcdefghijklmnopqrstuvwxyz
in the Auto activation triggers for Java
field.
See this question for more details.
You would get a type mismatch if Sheets(name).Cells(4 + i, 57)
contains a non-numeric value. You should validate the fields before you assume they are numbers and try to subtract from them.
Also, you should enable
Unfortunately Option Strict
so you are forced to explicitly convert your variables before trying to perform type-dependent operations on them such as subtraction. That will help you identify and eliminate issues in the future, too.Option Strict
is for VB.NET only. Still, you should look up best practices for explicit data type conversions in VBA.
Update:
If you are trying to go for the quick fix of your code, however, wrap the **
line and the one following it in the following condition:
If IsNumeric(Sheets(name).Cells(4 + i, 57))
Sheets(name).Cells(4 + i, 58) = Sheets(name).Cells(4 + i, 57) - a
x = Sheets(name).Cells(4 + i, 57) - a
End If
Note that your x
value may not contain its expected value in the next iteration, however.
This is a very simple solution using the tree
command in the directory you want to search for. -f
shows the full file path and |
is used to pipe the output of tree to grep
to find the file containing the string filename
in the name.
tree -f | grep filename
MYISAM:
INNODB:
for w64-based computers you have to install mingw64. If pkg-config.exe is missing then, you can refer to http://ftp.acc.umu.se/pub/gnome/binaries/win64/dependencies/
Unzip and copy/merge pkg-config.exe into your C:\mingw-w64 installation, eg. into on my pc into C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
Step 1, create a table, insert some rows:
create table penguins (id int primary key, myval varchar(50))
insert into penguins values(2, 'werrhhrrhrh')
insert into penguins values(25, 'weeehehehehe')
select * from penguins
Step 2, use mysql dump command:
mysqldump --no-data --skip-comments --host=your_database_hostname_or_ip.com -u your_username --password=your_password your_database_name penguins > penguins.sql
Step 3, observe the output in penguins.sql:
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
DROP TABLE IF EXISTS `penguins`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `penguins` (
`id` int(11) NOT NULL,
`myval` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
The output is cluttered by a number of executional-condition tokens above and below. You can filter them out if you don't want them in the next step.
Step 4 (Optional), filter out those extra executional-condition tokens this way:
mysqldump --no-data --skip-comments --compact --host=your_database_hostname_or_ip.com -u your_username --password=your_password your_database_name penguins > penguins.sql
Which produces final output:
eric@dev /home/el $ cat penguins.sql
DROP TABLE IF EXISTS `penguins`;
CREATE TABLE `penguins` (
`id` int(11) NOT NULL,
`myval` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Just use replace
instead of replaceAll
(which expects regex):
str = str.replace(",", ".");
or
str = str.replace(',', '.');
(replace
takes as input either char
or CharSequence
, which is an interface implemented by String
)
Also note that you should reassign the result
As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).
It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:
pagesize.c:
#include <unistd.h>
#include <stdio.h>
int main() {
int pageSize = getpagesize();
printf("Page size on your system = %i bytes\n", pageSize);
return 0;
}
Compile with gcc -o pagesize pagesize.c
then run ./pagesize
. My ubuntu server from Linode dutifully informs me the answer is 4k.
How to reproduce that error:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main() {
std::thread t1(task1, "hello");
return 0;
}
Compile and run:
el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)
You get that error because you didn't join or detach your thread.
One way to fix it, join the thread like this:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main() {
std::thread t1(task1, "hello");
t1.join();
return 0;
}
Then compile and run:
el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello
The other way to fix it, detach it like this:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main()
{
{
std::thread t1(task1, "hello");
t1.detach();
} //thread handle is destroyed here, as goes out of scope!
usleep(1000000); //wait so that hello can be printed.
}
Compile and run:
el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello
Read up on detaching C++ threads and joining C++ threads.
Definitely a late answer to this question. One possibility is to use the ListIterator in a for loop. It's not as clean as colon-syntax, but it works.
List<String> exampleList = new ArrayList<>();
exampleList.add("One");
exampleList.add("Two");
exampleList.add("Three");
//Forward iteration
for (String currentString : exampleList) {
System.out.println(currentString);
}
//Reverse iteration
for (ListIterator<String> itr = exampleList.listIterator(exampleList.size()); itr.hasPrevious(); /*no-op*/ ) {
String currentString = itr.previous();
System.out.println(currentString);
}
Credit for the ListIterator syntax goes to "Ways to iterate over a list in Java"
select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;
This is the fastest way to retrieve the row counts but there are a few important caveats:
ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE
(the default), or in earlier versions with ESTIMATE_PERCENT => 100
. See this post for an explanation of how
the AUTO_SAMPLE_SIZE algorithm works in 11g.LAST_ANALYZED
, the current results may be different.Sorry for replying on an older question, but I would like to clarify the last question.
You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:
https://www.google.com/search?g=[value from input-field]
But when you search with google, you notice the following URL:
https://www.google.nl/search?q=google+search+bar
Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.
Freely mixing flags between positional arguments:
./script.sh dumbo 127.0.0.1 --environment=production -q -d
./script.sh dumbo --environment=production 127.0.0.1 --quiet -d
can be accomplished with a fairly concise approach:
# process flags
pointer=1
while [[ $pointer -le $# ]]; do
param=${!pointer}
if [[ $param != "-"* ]]; then ((pointer++)) # not a parameter flag so advance pointer
else
case $param in
# paramter-flags with arguments
-e=*|--environment=*) environment="${param#*=}";;
--another=*) another="${param#*=}";;
# binary flags
-q|--quiet) quiet=true;;
-d) debug=true;;
esac
# splice out pointer frame from positional list
[[ $pointer -gt 1 ]] \
&& set -- ${@:1:((pointer - 1))} ${@:((pointer + 1)):$#} \
|| set -- ${@:((pointer + 1)):$#};
fi
done
# positional remain
node_name=$1
ip_address=$2
It's usualy clearer to not mix --flag=value
and --flag value
styles.
./script.sh dumbo 127.0.0.1 --environment production -q -d
This is a little dicey to read, but is still valid
./script.sh dumbo --environment production 127.0.0.1 --quiet -d
Source
# process flags
pointer=1
while [[ $pointer -le $# ]]; do
if [[ ${!pointer} != "-"* ]]; then ((pointer++)) # not a parameter flag so advance pointer
else
param=${!pointer}
((pointer_plus = pointer + 1))
slice_len=1
case $param in
# paramter-flags with arguments
-e|--environment) environment=${!pointer_plus}; ((slice_len++));;
--another) another=${!pointer_plus}; ((slice_len++));;
# binary flags
-q|--quiet) quiet=true;;
-d) debug=true;;
esac
# splice out pointer frame from positional list
[[ $pointer -gt 1 ]] \
&& set -- ${@:1:((pointer - 1))} ${@:((pointer + $slice_len)):$#} \
|| set -- ${@:((pointer + $slice_len)):$#};
fi
done
# positional remain
node_name=$1
ip_address=$2
Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with "ready".
How does this work? Well, JQuery adds an onunload event listener.
// http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { // ...
By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains.
[edit(Nickolay): here's why it works that way: webkit.org, developer.mozilla.org. Please read those articles (or my summary in a separate answer below) and consider whether you really need to do this and make your page load slower for your users.]
Can't believe it? Try this:
<body onunload=""><!-- This does the trick -->
<script type="text/javascript">
alert('first load / reload');
window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>
You will see similar results when using JQuery.
You may want to compare to this one without onunload
<body><!-- Will not reload on back button -->
<script type="text/javascript">
alert('first load / reload');
window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>
import java.io.*;
class Initials {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.print("Enter any sentence: ");
s = br.readLine();
s = " " + s; //adding a space infront of the inputted sentence or a name
s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
l = s.length(); //finding the length of the sentence
System.out.print("Output = ");
for (int i = 0; i < l; i++) {
x = s.charAt(i); //taking out one character at a time from the sentence
if (x == ' ') //if the character is a space, printing the next Character along with a fullstop
System.out.print(s.charAt(i + 1) + ".");
}
}
}
Shipping the database inside the apk and then copying it to /data/data/...
will double the size of the database (1 in apk, 1 in data/data/...
), and will increase the apk size (of course). So your database should not be too big.
In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".
To do so:
I'm leaving this here in the remote case it will help someone.
I used it installing the plugin "babel-plugin-inline-json-import" and then in .balberc add the plugin.
Install plugin
npm install --save-dev babel-plugin-inline-json-import
Config plugin in babelrc
"plugin": [ "inline-json-import" ]
And this is the code where I use it
import es from './es.json'
import en from './en.json'
export const dictionary = { es, en }
The Header
field of the Request is public. You may do this :
req.Header.Set("name", "value")
Try this
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
// do some work
}
There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self
in a default parameter and will never be able to.
You need reinstall VS.
Language Pack Support in Visual Studio 2017 RC
Issue:
This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.
Workaround:
These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.
Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016
You can read it from Request
using Request.Form
, your dropdown name is ddlVendor
so pass ddlVendor
key in the formCollection to get its value that is posted by form:
string strDDLValue = Request.Form["ddlVendor"].ToString();
or Use FormCollection
:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["ddlVendor"].ToString();
return View(MV);
}
If you want with Model binding then add a property in Model:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVendor {get;set;}
}
and in View:
@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
and in Action:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}
If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectVendor {get;set;}
public string SelectedvendorText { get; set; }
}
use jquery to set hidden field:
<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
$("#SelectedvendorText").val($(this).text());
});
});
</script>
@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)
shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while...loop
import os
import shutil
shutil.rmtree(path)
while os.path.exists(path):
pass
print('done')
You can use "os.sep "
import os
pathfile=os.path.dirname(templateFile)
directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
rootTree.write(directory)
For OGG on Windows: Theoraconverter
Just for reference, here is a benchmark of different technique rendering performances,
http://jsperf.com/zp-string-concatenation/6
m,
To get started, you should download the source code from Github, by following the instructions here (you'll need Bazel and a recent version of GCC).
The C++ API (and the backend of the system) is in tensorflow/core
. Right now, only the C++ Session interface, and the C API are being supported. You can use either of these to execute TensorFlow graphs that have been built using the Python API and serialized to a GraphDef
protocol buffer. There is also an experimental feature for building graphs in C++, but this is currently not quite as full-featured as the Python API (e.g. no support for auto-differentiation at present). You can see an example program that builds a small graph in C++ here.
The second part of the C++ API is the API for adding a new OpKernel
, which is the class containing implementations of numerical kernels for CPU and GPU. There are numerous examples of how to build these in tensorflow/core/kernels
, as well as a tutorial for adding a new op in C++.
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the HTML code
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace
method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
You can alter the number of decimal places by varying the value passed into the toFixed()
method. See MDN docs.
toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer
You have a couple of things fighting in your strings.
mysql_real_escape_string()
)It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.
One way is to use the lattice package and xyplot():
R> DF <- data.frame(x=1:10, y=rnorm(10)+5,
+> z=sample(letters[1:3], 10, replace=TRUE))
R> DF
x y z
1 1 3.91191 c
2 2 4.57506 a
3 3 3.16771 b
4 4 5.37539 c
5 5 4.99113 c
6 6 5.41421 a
7 7 6.68071 b
8 8 5.58991 c
9 9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))
By giving explicit grouping information via variable z
, you obtain different colors. You can specify colors etc, see the lattice documentation.
Because z
here is a factor variable for which we obtain the levels (== numeric indices), you can also do
R> with(DF, plot(x, y, col=z))
but that is less transparent (to me, at least :) then xyplot()
et al.
Assuming your data is in column A, add a formula to column B
="'" & A1 & "'"
and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.
I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.
So here is what I came up with:
;(function(defaults, $, undefined) {
var getSubmitHandler = function(onsubmit, success, error) {
return function(event) {
if (typeof onsubmit === 'function') {
onsubmit.call(this, event);
}
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function() {
if (typeof success === 'function') {
success.apply(this, arguments);
}
}).fail(function() {
if (typeof error === 'function') {
error.apply(this, arguments);
}
});
event.preventDefault();
};
};
$.fn.extend({
// Usage:
// jQuery(selector).ajaxForm({
// onsubmit:function() {},
// success:function() {},
// error: function() {}
// });
ajaxForm : function(options) {
options = $.extend({}, defaults, options);
return $(this).each(function() {
$(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
});
}
});
})({}, jQuery);
This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:
$('form').ajaxForm({
onsubmit: function(event) {
// User submitted the form
},
success: function(data, textStatus, jqXHR) {
// The form was successfully submitted
},
error: function(jqXHR, textStatus, errorThrown) {
// The submit action failed
}
});
Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.
Update:
This feature is now part of the proplot matplotlib package that I recently released on pypi. By default, when you make figures, the labels are "shared" between axes.
Original answer:
I discovered a more robust method:
If you know the bottom
and top
kwargs that went into a GridSpec
initialization, or you otherwise know the edges positions of your axes in Figure
coordinates, you can also specify the ylabel position in Figure
coordinates with some fancy "transform" magic. For example:
import matplotlib.transforms as mtransforms
bottom, top = .1, .9
f, a = plt.subplots(nrows=2, ncols=1, bottom=bottom, top=top)
avepos = (bottom+top)/2
a[0].yaxis.label.set_transform(mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), f.transFigure # specify x, y transform
)) # changed from default blend (IdentityTransform(), a[0].transAxes)
a[0].yaxis.label.set_position((0, avepos))
a[0].set_ylabel('Hello, world!')
...and you should see that the label still appropriately adjusts left-right to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always exactly between the desired subplots.
Furthermore, if you don't even use set_position
, the ylabel will show up by default exactly halfway up the figure. I'm guessing this is because when the label is finally drawn, matplotlib
uses 0.5 for the y
-coordinate without checking whether the underlying coordinate transform has changed.
I've just downloaded SQL Developer 4.0 for OS X (10.9), it just got out of beta. I also downloaded the latest Postgres JDBC jar. On a lark I decided to install it (same method as other third party db drivers in SQL Dev), and it accepted it. Whenever I click "new connection", there is a tab now for Postgres... and clicking it shows a panel that asks for the database connection details.
The answer to this question has changed, whether or not it is supported, it seems to work. There is a "choose database" button, that if clicked, gives you a dropdown list filled with available postgres databases. You create the connection, open it, and it lists the schemas in that database. Most postgres commands seem to work, though no psql commands (\list, etc).
Those who need a single tool to connect to multiple database engines can now use SQL Developer.
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
this should solve your problem
I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .
I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.
I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php
and ends with ?>
.
You can embed PHP code inside HTML like this (you have to save the file using .php
extension to let PHP server recognize and process it, ie: index.php):
<body>
<?php echo "<div>Hello World!</div>" ?>
</body>
or you can use a whole php file, ie: test.php:
<?php
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file
there's no document.ready
in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
Max OS: If you want to toggle comment multiple individual lines versus block comment an entire selection, you can do multi line edit, shift+cmd+L, then cmd+/ in that sequence.
Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:
$('#yourDivName').html('yourtHTML');
You may also consider using:
$('#yourDivName').append('yourtHTML');
This will add your gallery as the last item in the selected div. Or:
$('#yourDivName').prepend('yourtHTML');
This will add it as the first item in the selected div.
See the JQuery docs for these functions:
Use the isin
method:
rpt[rpt['STK_ID'].isin(stk_list)]
In case you want a single line of code:
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
The result is "2016-09-25 16:50:34"
This seems very easy:
>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6
However if you like something like a function do as this:
def insert_dash(string, index):
return string[:index] + '-' + string[index:]
print insert_dash("355879ACB6", 5)
I had this problem on Windows.
My problem was that my %GOPATH%
environment variable was set to
C:\Users\john\src\goworkspace
instead of
C:\Users\john\src\goworkspace\
Adding the missing trailing slash at the end fixed it for me.
On Windows, Chrome might be installed in your AppData folder:
"C:\Users\\AppData\Local\Google\Chrome\Application"
Before you execute the command, make sure all of your Chrome windows are closed and not otherwise running. Or, the command line param would not be effective.
chrome.exe --allow-file-access-from-files
The classic response is, "You don't." You test the public API of Foo
, not its internals.
Is there any behavior of the Foo
object (or, less good, some other object in the environment) that is affected by foo()
? If so, test that. And if not, what does the method do?
If you want to call it more like Math.Max, you can do something like this very short expression body:
public static DateTime Max(params DateTime[] dates) => dates.Max();
[...]
var lastUpdatedTime = DateMath.Max(feedItemDateTime, assemblyUpdatedDateTime);
Javac Reporter.java
java Reporter
Similarily, you can set it in windows environment variables. for example, in Win7
Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila
The documentation says it best and includes an example, (highlighting mine).
android:weightSum
Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.
So to correct superM's example, suppose you have a LinearLayout
with horizontal orientation that contains two ImageViews
and a TextView
with. You define the TextView
to have a fixed size, and you'd like the two ImageViews
to take up the remaining space equally.
To accomplish this, you would apply layout_weight
1 to each ImageView
, none on the TextView
, and a weightSum
of 2.0 on the LinearLayout
.
I had the same issue, I created a new project and copied the web.config files as recommended in the answer by Gupta, but that didn't fix things for me. I checked answer by Alex and Liam, I thought this line must have been copied from the new web.config, but it looks like the new project itself didn't have this line (MVC5):
<add key="webpages:Version" value="3.0.0.0" />
Adding the line to the views/web.config file solved the issue for me.
The suggested solutions are incompatible with Seaborn 0.8.1
giving the following errors because the Seaborn interface has changed:
AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure
AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function
The following calls allow you to access the figure (Seaborn 0.8.1 compatible):
swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...)
as seen previously in this answer.
UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by
fig = myGridPlotObject.fig
Like previously suggested in other posts in this thread.
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
Edit your package.json:
"build": "react-scripts build && mv build webapp"
Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe
The code is simple, just type:
import pyarrow.parquet as pq
df = pq.read_table(source=your_file_path).to_pandas()
For more information, see the document from Apache pyarrow Reading and Writing Single Files
you must compile the file with c++11 support
g++ -std=c++0x -o test example.cpp
You can save effort with the new AsyncEnumerator NuGet Package, which didn't exist 4 years ago when the question was originally posted. It allows you to control the degree of parallelism:
using System.Collections.Async;
...
await ids.ParallelForEachAsync(async i =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = await repo.GetCustomer(i);
customers.Add(cust);
},
maxDegreeOfParallelism: 10);
Disclaimer: I'm the author of the AsyncEnumerator library, which is open source and licensed under MIT, and I'm posting this message just to help the community.
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
This did the trick for me:
sudo pip install scrapy --ignore-installed six
cd into the repo/directory that you're pushing into on the remote machine and enter
$ git config core.bare true
The solution is to compare Input::old()
with the $key
variable.
@if (Input::old('title') == $key)
<option value="{{ $key }}" selected>{{ $val }}</option>
@else
<option value="{{ $key }}">{{ $val }}</option>
@endif
One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use
Do .libPaths()
, close every R runing, check in the first directory, remove the zoo
package restart R and install
zoo
again. Of course you need to have sufficient rights.
Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}"
on the html input.
The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
I was also facing the same issue.
I was using the code below in .aspx page without writing authentication configuration in web.config file. After writing the settings in Web.config, I am able to run my code.
<% If Request.IsAuthenticated Then%>
<table></table>
<%end if%>
clone() was designed with several mistakes (see this question), so it's best to avoid it.
From Effective Java 2nd Edition, Item 11: Override clone judiciously
Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.
This book also describes the many advantages copy constructors have over Cloneable/clone.
All standard collections have copy constructors. Use them.
List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);
It means something like this:
std::vector<Movie *> movies;
Then you add to the vector as you read lines:
movies.push_back(new Movie(...));
Remember to delete all of the Movie*
objects once you are done with the vector.
Option Explicit
Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook
TitleId = 4
Resultid = 0
Dim FileName1, FileName2 As String
Dim Difference As Long
'TestPassCount = 0
'TestFailCount = 0
'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count
If (TestDataRowCount <= 2) Then
MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
For RecordId = 3 To TestDataRowCount
RefreshResultSheet
'Source File row count
SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
Set sourcewb = Workbooks.Open(SrceFile)
With sourcewb.Worksheets(1)
SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
sourcewb.Close
End With
'Target File row count
TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
Set targetwb = Workbooks.Open(TrgtFile)
With targetwb.Worksheets(1)
TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
targetwb.Close
End With
' Set Row Count Result Test data value
TitleId = TitleId + 3
Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value
'Compare Source and Target Row count
Resultid = TitleId + 1
Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
If (SourceRowCount = TargetRowCount) Then
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestPassCount = TestPassCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
TestFailCount = TestFailCount + 1
End If
'For comparison of two files
FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
FileName2 = Worksheets("TestData").Range("E" & RecordId).Value
Set myWorkbook1 = Workbooks.Open(FileName1)
Set myWorkbook2 = Workbooks.Open(FileName2)
Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
myWorkbook1.Close
myWorkbook2.Close
'MsgBox Difference
'Set Result of data validation in result sheet
Resultid = Resultid + 1
Worksheets("Result").Activate
Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"
If Difference > 0 Then
Worksheets("Result").Range("B" & Resultid).Value = "Failed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestFailCount = TestFailCount + 1
Else
Worksheets("Result").Range("B" & Resultid).Value = "Passed"
Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
TestPassCount = TestPassCount + 1
End If
Next RecordId
End If
UpdateTestExecData TestPassCount, TestFailCount
End Sub
Sub RefreshResultSheet()
Worksheets("Result").Activate
Worksheets("Result").Range("B1:B4").Select
Selection.ClearContents
Worksheets("Result").Range("D1:D4").Select
Selection.ClearContents
Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub
Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
Worksheets("Result").Range("D2").Value = TestPassCount
Worksheets("Result").Range("D3").Value = TestFailCount
Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub
Try to implement dynamic data structure such as a linked list
Check if it's on first. That should get rid of the warning and it'll ensure that if your code is run on older versions of PHP that magic quotes are indeed off.
Don't just remove that line of code as suggested by others unless you can be 100% sure that the code will never be run on anything before PHP 5.3.
<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
// Deactivate
set_magic_quotes_runtime(false);
}
?>
get_magic_quotes_runtime
is NOT deprecated in PHP 5.3.
Source: http://us2.php.net/get_magic_quotes_runtime/
Move the session_start();
to top of the page always.
<?php
@ob_start();
session_start();
?>
Cellpadding
is the amount of space between the outer edges of the
table cell and the content of the cell.
Cellspacing
is the amount of space in between the individual table cells.
More Details *Link 1*
I also experienced an issue like this, my workspace was corrupted and didn't do all the important things anymore.
For some reason, I had a corrupt resource on one of my projects. It didn't show up in the package tree, but it did show in the error log in Eclipse as
Error while creating a link for external folder X:\somefolder
After checking every project (because the error didn't point to one), I indeed found this resource in one of the build paths (in Configure Build Path menu it did show an error icon!) and deleted it.
See Eclipse (Kepler) Workspace acting weird (type hierarchy, searching for references not working) for a wider description of my issue if you're experiencing something similar.
Posted this for future developers to reference.
When using MVC in .NET with Angular you can always use OrderByDecending() when doing your db query like this:
var reversedList = dbContext.GetAll().OrderByDecending(x => x.Id).ToList();
Then on the Angular side, it will already be reversed in some browsers (IE). When supporting Chrome and FF, you would then need to add orderBy:
<tr ng-repeat="item in items | orderBy:'-Id'">
In this example, you'd be sorting in descending order on the .Id property. If you're using paging, this gets more complicated because only the first page would be sorted. You'd need to handle this via a .js filter file for your controller, or in some other way.
This isn't the exact answer you are looking for but it was a solution that i needed on my project and hope this helps someone. This will list 1 to n row items separated by commas. Group_Concat makes this possible in MySQL.
select
cemetery.cemetery_id as "Cemetery_ID",
GROUP_CONCAT(distinct(names.name)) as "Cemetery_Name",
cemetery.latitude as Latitude,
cemetery.longitude as Longitude,
c.Contact_Info,
d.Direction_Type,
d.Directions
from cemetery
left join cemetery_names on cemetery.cemetery_id = cemetery_names.cemetery_id
left join names on cemetery_names.name_id = names.name_id
left join cemetery_contact on cemetery.cemetery_id = cemetery_contact.cemetery_id
left join
(
select
cemetery_contact.cemetery_id as cID,
group_concat(contacts.name, char(32), phone.number) as Contact_Info
from cemetery_contact
left join contacts on cemetery_contact.contact_id = contacts.contact_id
left join phone on cemetery_contact.contact_id = phone.contact_id
group by cID
)
as c on c.cID = cemetery.cemetery_id
left join
(
select
cemetery_id as dID,
group_concat(direction_type.direction_type) as Direction_Type,
group_concat(directions.value , char(13), char(9)) as Directions
from directions
left join direction_type on directions.type = direction_type.direction_type_id
group by dID
)
as d on d.dID = cemetery.cemetery_id
group by Cemetery_ID
This cemetery has two common names so the names are listed in different rows connected by a single id but two name ids and the query produces something like this
CemeteryID Cemetery_Name Latitude
1 Appleton,Sulpher Springs 35.4276242832293
This is likely because you haven't set your compileSdkVersion
to 21 in your build.gradle file. You also probably want to change your targetSdkVersion
to 21.
android {
//...
compileSdkVersion 21
defaultConfig {
targetSdkVersion 21
}
//...
}
This requires you to have downloaded the latest SDK updates to begin with.
Once you've downloaded all the updates (don't forget to also update the Android Support Library/Repository, too!) and updated your compileSdkVersion, re-sync your Gradle project.
Edit: For Eclipse or general IntelliJ users
See reVerse's answer. He has a very thorough walk through!
Since .NET 4.5 the Validators use data-attributes and bounded Javascript to do the validation work, so .NET expects you to add a script reference for jQuery.
There are two possible ways to solve the error:
Disable UnobtrusiveValidationMode
:
Add this to web.config:
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
It will work as it worked in previous .NET versions and will just add the necessary Javascript to your page to make the validators work, instead of looking for the code in your jQuery file. This is the common solution actually.
Another solution is to register the script:
In Global.asax Application_Start
add mapping to your jQuery file path:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
new ScriptResourceDefinition
{
Path = "~/scripts/jquery-1.7.2.min.js",
DebugPath = "~/scripts/jquery-1.7.2.js",
CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
});
}
Some details from MSDN:
ValidationSettings:UnobtrusiveValidationMode Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.
If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic.
If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.
This is an old question, but because this might help a lot of c# coders out there, there is an easy way to solve this right now as follows:
if ((dataTableName?.Rows?.Count ?? 0) > 0)
Just make sur that the static option is set to false
@ViewChild('contentPlaceholder', {static: false}) contentPlaceholder: ElementRef;
You can use the Material Components Library and the MaterialButton
component.
Use the app:icon
and app:iconGravity="start"
attributes.
Something like:
<com.google.android.material.button.MaterialButton
style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/..."
app:iconGravity="start"
../>
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
The VBScript Messagebox is fairly limited as to the labels you can apply to the buttons, your choices are pretty much limited to:
So you are going to have to build your own form if you want "ON"/"OFF"
Better yet, why not rephrase the prompt in the box so one of the above options works.
For example:
Do you want the light on?
[Yes] [No]
And for God's sake don't do one of these UI monstrosities!
Switch setting? (Click "yes" for ON and "No" for Off)
[Yes] [No]
Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat
Will also work
How about giving the port number while invoking the command without need to change anything in your application code or environment files? That way it is possible running and serving same code base from several different ports.
like:
$ export PORT=4000 && npm start
You can put the port number you like in place of the example value 4000
above.
ORA-01861: literal does not match format string
This happens because you have tried to enter a literal with a format string, but the length of the format string was not the same length as the literal.
You can overcome this issue by carrying out following alteration.
TO_DATE('1989-12-09','YYYY-MM-DD')
As a general rule, if you are using the TO_DATE function, TO_TIMESTAMP function, TO_CHAR function, and similar functions, make sure that the literal that you provide matches the format string that you've specified
The correct answer is, that, because the '%'
-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName
(be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'
or, in your example:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'