This is my code for a function that gets the tasks and gets their names, also adding them into a list to be accessed from a list. It creates temp files with the data, reads the files and gets the task name with the .exe suffix, and arranges the files to be deleted when the program has exited with System.exit(0), it also hides the processes being used to get the tasks and also java.exe so that the user can't accidentally kill the process that runs the program all together.
private static final DefaultListModel tasks = new DefaultListModel();
public static void getTasks()
{
new Thread()
{
@Override
public void run()
{
try
{
File batchFile = File.createTempFile("batchFile", ".bat");
File logFile = File.createTempFile("log", ".txt");
String logFilePath = logFile.getAbsolutePath();
try (PrintWriter fileCreator = new PrintWriter(batchFile))
{
String[] linesToPrint = {"@echo off", "tasklist.exe >>" + logFilePath, "exit"};
for(String string:linesToPrint)
{
fileCreator.println(string);
}
fileCreator.close();
}
int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();
if(task == 0)
{
FileReader fileOpener = new FileReader(logFile);
try (BufferedReader reader = new BufferedReader(fileOpener))
{
String line;
while(true)
{
line = reader.readLine();
if(line != null)
{
if(line.endsWith("K"))
{
if(line.contains(".exe"))
{
int index = line.lastIndexOf(".exe", line.length());
String taskName = line.substring(0, index + 4);
if(! taskName.equals("tasklist.exe") && ! taskName.equals("cmd.exe") && ! taskName.equals("java.exe"))
{
tasks.addElement(taskName);
}
}
}
}
else
{
reader.close();
break;
}
}
}
}
batchFile.deleteOnExit();
logFile.deleteOnExit();
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException | InterruptedException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (NullPointerException ex)
{
// This stops errors from being thrown on an empty line
}
}
}.start();
}
public static void killTask(String taskName)
{
new Thread()
{
@Override
public void run()
{
try
{
Runtime.getRuntime().exec("taskkill.exe /IM " + taskName);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
Out of object in PHP. Given array of coordinate pairs, returns center.
/**
* Calculate center of given coordinates
* @param array $coordinates Each array of coordinate pairs
* @return array Center of coordinates
*/
function getCoordsCenter($coordinates) {
$lats = $lons = array();
foreach ($coordinates as $key => $value) {
array_push($lats, $value[0]);
array_push($lons, $value[1]);
}
$minlat = min($lats);
$maxlat = max($lats);
$minlon = min($lons);
$maxlon = max($lons);
$lat = $maxlat - (($maxlat - $minlat) / 2);
$lng = $maxlon - (($maxlon - $minlon) / 2);
return array("lat" => $lat, "lon" => $lng);
}
Taken idea from #4
[quote from http://www.javabeat.net/session-factory-hibernate-4/]
There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.
Supporting ownership
, maximum number of processes share lock
and the maximum number of allowed processes/threads in critical section
are three major factors that determine the name/type of the concurrent object with general name of lock
. Since the value of these factors are binary (have two states), we can summarize them in a 3*8 truth-like table.
X Y Z Name
--- --- --- ------------------------
0 8 8 Semaphore
0 8 1 Binary Semaphore
0 1 8 SemaphoreSlim
0 1 1 Binary SemaphoreSlim(?)
1 8 8 Recursive-Mutex(?)
1 8 1 Mutex
1 1 8 N/A(?)
1 1 1 Lock/Monitor
Feel free to edit or expand this table, I've posted it as an ascii table to be editable:)
Here is a way:
div {_x000D_
..._x000D_
overflow: hidden;_x000D_
border-radius: 14px;_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
table {_x000D_
border-spacing: 0;_x000D_
}
_x000D_
<div>_x000D_
<table></table>_x000D_
</div>
_x000D_
Or
div {
...
overflow: hidden;
border-radius: 14px;
position: relative;
z-index: 1;
}
It sets result
to the (unsigned) value resulting from putting the 8 bits of value
in the lowest 8 bits of result
.
The reason something like this is necessary is that byte
is a signed type in Java. If you just wrote:
int result = value;
then result
would end up with the value ff ff ff fe
instead of 00 00 00 fe
. A further subtlety is that the &
is defined to operate only on int
values1, so what happens is:
value
is promoted to an int
(ff ff ff fe
).0xff
is an int
literal (00 00 00 ff
).&
is applied to yield the desired value for result
.(The point is that conversion to int
happens before the &
operator is applied.)
1Well, not quite. The &
operator works on long
values as well, if either operand is a long
. But not on byte
. See the Java Language Specification, sections 15.22.1 and 5.6.2.
Try this, it's called Firebug Lite and apparently works with the beta version of Chrome.
You can also find it at: https://chrome.google.com/extensions/
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
package lecture3;
import java.util.Scanner;
public class divisibleBy2and5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter an integer number:");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
if (x % 2==0){
System.out.println("The integer number you entered is divisible by 2");
}
else{
System.out.println("The integer number you entered is not divisible by 2");
if(x % 5==0){
System.out.println("The integer number you entered is divisible by 5");
}
else{
System.out.println("The interger number you entered is not divisible by 5");
}
}
}
}
parentElement.prepend(newFirstChild);
This is a new addition in (likely) ES7. It is now vanilla JS, probably due to the popularity in jQuery. It is currently available in Chrome, FF, and Opera. Transpilers should be able to handle it until it becomes available everywhere.
P.S. You can directly prepend strings
parentElement.prepend('This text!');
Links: developer.mozilla.org - Polyfill
You can use the function array_key_exists
to do that.
For example,
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
PS : Example taken from here.
I'd have thought you need to use a MessageFormat rather than DecimalFormat. That should be more flexible.
As you correctly point out, one can ReDim Preserve
only the last dimension of an array (ReDim Statement on MSDN):
If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array
Hence, the first issue to decide is whether 2-dimensional array is the best data structure for the job. Maybe, 1-dimensional array is a better fit as you need to do ReDim Preserve
?
Another way is to use jagged array as per Pieter Geerkens's suggestion. There is no direct support for jagged arrays in VB6. One way to code "array of arrays" in VB6 is to declare an array of Variant
and make each element an array of desired type (String
in your case). Demo code is below.
Yet another option is to implement Preserve
part on your own. For that you'll need to create a copy of data to be preserved and then fill redimensioned array with it.
Option Explicit
Public Sub TestMatrixResize()
Const MAX_D1 As Long = 2
Const MAX_D2 As Long = 3
Dim arr() As Variant
InitMatrix arr, MAX_D1, MAX_D2
PrintMatrix "Original array:", arr
ResizeMatrix arr, MAX_D1 + 1, MAX_D2 + 1
PrintMatrix "Resized array:", arr
End Sub
Private Sub InitMatrix(a() As Variant, n As Long, m As Long)
Dim i As Long, j As Long
Dim StringArray() As String
ReDim a(n)
For i = 0 To n
ReDim StringArray(m)
For j = 0 To m
StringArray(j) = i * (m + 1) + j
Next j
a(i) = StringArray
Next i
End Sub
Private Sub PrintMatrix(heading As String, a() As Variant)
Dim i As Long, j As Long
Dim s As String
Debug.Print heading
For i = 0 To UBound(a)
s = ""
For j = 0 To UBound(a(i))
s = s & a(i)(j) & "; "
Next j
Debug.Print s
Next i
End Sub
Private Sub ResizeMatrix(a() As Variant, n As Long, m As Long)
Dim i As Long
Dim StringArray() As String
ReDim Preserve a(n)
For i = 0 To n - 1
StringArray = a(i)
ReDim Preserve StringArray(m)
a(i) = StringArray
Next i
ReDim StringArray(m)
a(n) = StringArray
End Sub
The usual way to find just the common elements in a set is to use Python's set
class. Just add all the elements to the set, then convert the set to a list
, and bam the duplicates are gone.
The problem, of course, is that a set()
can only contain hashable entries, and a dict
is not hashable.
If I had this problem, my solution would be to convert each dict
into a string that represents the dict
, then add all the strings to a set()
then read out the string values as a list()
and convert back to dict
.
A good representation of a dict
in string form is JSON format. And Python has a built-in module for JSON (called json
of course).
The remaining problem is that the elements in a dict
are not ordered, and when Python converts the dict
to a JSON string, you might get two JSON strings that represent equivalent dictionaries but are not identical strings. The easy solution is to pass the argument sort_keys=True
when you call json.dumps()
.
EDIT: This solution was assuming that a given dict
could have any part different. If we can assume that every dict
with the same "id"
value will match every other dict
with the same "id"
value, then this is overkill; @gnibbler's solution would be faster and easier.
EDIT: Now there is a comment from André Lima explicitly saying that if the ID is a duplicate, it's safe to assume that the whole dict
is a duplicate. So this answer is overkill and I recommend @gnibbler's answer.
Use the enumerate
built-in function: http://docs.python.org/library/functions.html#enumerate
I've just fixed this for my machine. Maybe it will work for some. Maybe not for others, but here is what worked for me.
In IIS, I had to add bindings for https to the default website (or, I suppose, the website you are running the app under).
Now my localhost works when debugging from Visual Studio.
Using Python 3 you can have both required and non-required keyword arguments:
Optional: (default value defined for param 'b')
def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
Required (no default value defined for param 'b'):
def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.
go to python/scripts folder, open a command window to this path, type the following:
C:\python34\scripts> python -m pip install pygame
To test it, open python IDE and type
import pygame
print (pygame.ver)
It worked for me...
So you use this:
var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");
and if you open a MVC Partial View in Dialog, you can create in index a hidden button and JQUERY click event:
$("#YourButton").click(function()
{
theDialog.dialog("open");
OR
theDialog.dialog("close");
});
then inside partial view html you call button trigger click like:
$("#YouButton").trigger("click")
see ya.
In my case - I found a process called
cb_console_runner
I stopped this process and things were ok again.
I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up. As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesEclipse doesn't consult the
JAVA_HOME
variable
You should specify where Eclipse should find your JDK in the file eclipse.ini
. Specifically, the following parameter (note that it is 2 separate lines in the ini file):
-vm
C:\Java\JDK\1.8\bin\javaw.exe
or wherever your javaw.exe happens to be.
Note: The format of the ini
file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right.
FWIW, you can provide an error message like so:
USERNAME=${1:?"Specify a username"}
This displays a message like this and exits with code 1:
./myscript.sh
./myscript.sh: line 2: 1: Specify a username
A more complete example of everything:
#!/bin/bash
ACTION=${1:?"Specify 'action' as argv[1]"}
DIRNAME=${2:-$PWD}
OUTPUT_DIR=${3:-${HOMEDIR:-"/tmp"}}
echo "$ACTION"
echo "$DIRNAME"
echo "$OUTPUT_DIR"
Output:
$ ./script.sh foo
foo
/path/to/pwd
/tmp
$ export HOMEDIR=/home/myuser
$ ./script.sh foo
foo
/path/to/pwd
/home/myuser
$ACTION
takes the value of the first argument, and exits if empty$DIRNAME
is the 2nd argument, and defaults to the current directory$OUTPUT_DIR
is the 3rd argument, or $HOMEDIR
(if defined), else, /tmp
. This works on OS X, but I'm not positive that it's portable.This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:
render = () => null
This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render
function and this is the most concise form satisfying this requirement that I can think of.
I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router
documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.
Based on the syntax provided
Select * Where Amount = min(Amount)
You could do using:
library(sqldf)
Using @Kara Woo's example df
sqldf("select * from df where Amount in (select min(Amount) from df)")
#Name Amount
#1 B 120
#2 E 120
Well best option is %java_home%\bin\xjc -p [your namespace] [xsd_file].xsd
.
I also have a question if we have an option to do reverse engineering here. if yes can we generate xsd from pojo class?
just use this simple code: First add dependency :
implementation 'de.hdodenhof:circleimageview:2.2.0'
then add in xml layout the following code:-
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/Imgshaligram"
android:layout_width="96dp"
android:layout_height="96dp"
android:src="@drawable/shaligram"
app:civ_border_color="#d1b1b1"
android:foregroundGravity="center"/>
This worked for me:
foreach (var item in FirmNameList){
if (FirmNames != "")
{
FirmNames += ",\r\n"
}
FirmNames += item;
}
And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.
ALTER TABLE foo CHECK CONSTRAINT ALL
or
ALTER TABLE foo CHECK CONSTRAINT FK_something
then you can run back in and do an update against any checked columns like so:
UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc
And any errors at that point will be due to failure to meet constraints.
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1
To get a list of ten samples:
>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/
I'd like to demonstrate that if you convert to .Date that you don't need to worry about hours/mins/seconds etc:
[Test]
public void ConvertToDateWillHaveTwoDatesEqual()
{
DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
Assert.IsTrue(d1 < d2);
DateTime d3 = new DateTime(2008, 1, 1,7,0,0);
DateTime d4 = new DateTime(2008, 1, 1,10,0,0);
Assert.IsTrue(d3 < d4);
Assert.IsFalse(d3.Date < d4.Date);
}
MyEclipse (eclipse based, subscription required) and Webclipse (an eclipse plug-in, currently free), from my company, Genuitec, have newly engineered (as of 2015) JavaScript debugging built in:
You can debug both generic web applications and Node.js files.
In my case, I have given this attribute to the input tag
data-date-start-date="0d"
data-date-end-date="0d"
mysqli_fetch_array()
returns NULL
if there is no row.
In procedural style:
if ( ! $row = mysqli_fetch_array( $result ) ) {
... no result ...
}
else {
... get the first result in $row ...
}
In Object oriented style:
if ( ! $row = $result->fetch_array() ) {
...
}
else {
... get the first result in $row ...
}
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
Complementing the accepted answer, if you use SELECT2 plugin, you need to recall select2 script to make changes is all select2 fields:
function resetForm(formId){
$('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
$('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
$('.select2').select2();
}
In postgres 12 I needed to use this command:
UPDATE DATABASECHANGELOGLOCK SET LOCKED=false, LOCKGRANTED=null, LOCKEDBY=null where ID=1;
public byte UserType
public string SelectUserType
You need to get one and set different one. Selected value can not be the same item that you are about to set.
@Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType))
I use Enum dictionary for my list, that's why there is "key", "value" pair.
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... prints -2
and 12
.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \
as \\
in a Java String though. So, \d+ matches 1 or more digits.
An other very good documentation tool is sphinx. It will be used for the upcoming python 2.6 documentation and is used by django and a lot of other python projects.
From the sphinx website:
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
With typescript 2.8, you can use the new built-in Exclude
type. The 2.8 release notes actually mention this in the section "Predefined conditional types":
Note: The Exclude type is a proper implementation of the Diff type suggested here. [...] We did not include the Omit type because it is trivially written as
Pick<T, Exclude<keyof T, K>>
.
Applying this to your example, type XY could be defined as:
type XY = Pick<XYZ, Exclude<keyof XYZ, "z">>
After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below
sudo mysql -u root
Then run the commands below to use the mysql database.
use mysql;
Finally, run the commands below to reset the root password.
update user set password=PASSWORD("new_password_here") where User='root';
Replace new_password _here with the new password you want to create for the root account, then press Enter.
After that, run the commands below to update the permissions and save your changes to disk.
flush privileges;
Exit (CTRL + D) and you’re done.
Next start MariaDB normally and test the new password you just created.
sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service
Logon to the database by running the commands below.
sudo mysql -u root -p
source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/
In the app build.gradle
dependency, you must add the following code
classpath 'com.google.gms:google-services:$last_version'
And then please check the Google Play Service SDK tools installing status.
To insert the Value into the Dictionary
Dictionary<string, string> dDS1 = new Dictionary<string, string>();//Declaration
dDS1.Add("VEqpt", "aaaa");//adding key and value into the dictionary
string Count = dDS1["VEqpt"];//assigning the value of dictionary key to Count variable
dDS1["VEqpt"] = Count + "bbbb";//assigning the value to key
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
Static Variables:
Const Variables:
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Got help from this discussion. In my case the
git reset HEAD subby
git commit
worked for me :)
Make sure to check the schema at the database level directly. I've gotten burned by this before, where, for example, a migration was initially written to create a :datetime column, and I ran it locally, then tweaked the migration to a :date before actually deploying. Thus everyone's database looks good except for mine, and the bugs are subtle.
I always liked this (you could modify as appropriate):
public static IEnumerable<TEnum> GetEnumValues()
{
Type enumType = typeof(TEnum);
if(!enumType.IsEnum)
throw new ArgumentException("Type argument must be Enum type");
Array enumValues = Enum.GetValues(enumType);
return enumValues.Cast<TEnum>();
}
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];
var json = "{ ";
for(var i = 0; i < key.length; i++) {
(i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
$(document).ready(function(){_x000D_
$('input').on("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
Try this :
$obj = @{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
This usually occurs when the master.mdf or the mastlog.ldf gets corrupt . In order to solve the issue goto the following path C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL
, there you will find a folder ” Template Data ” , copy the master.mdf and mastlog.ldf and replace it in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Data folder
. Thats it . Now start the MS SQL service and you are done
My solution was to select the maven profiles I had defined in my pom.xml in which I had declared the hibernate dependencies.
CTRL + ALT + P
in eclipse.
In my project I was experiencing this problem and many others because in my pom I have different profiles for supporting Glassfish 3, Glassfish 4 and also WildFly so I have differet versions of Hibernate per container as well as different Java compilation targets and so on. Selecting the active maven profiles resolved my issue.
int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Output of randomWithRange(2, 5)
10 times:
5
2
3
3
2
4
4
4
5
4
The bounds are inclusive, ie [2,5], and min
must be less than max
in the above example.
EDIT: If someone was going to try and be stupid and reverse min
and max
, you could change the code to:
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: For your question about double
s, it's just:
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
And again if you want to idiot-proof it it's just:
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}
First of all, make sure the mysql service is running:
ps elf|grep mysql
you will see an output like this if is running:
4 S root 9642 1 0 80 0 - 2859 do_wai 23:08 pts/0 00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/tomcat-machine.local.pid
4 S mysql 9716 9642 0 80 0 - 200986 poll_s 23:08 pts/0 00:00:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/lib/mysql/tomcat-machine.local.err --pid-file=/var/lib/mysql/tomcat-machine.local.pid
then change localhost to 127.0.0.1 in config.inc.php
$cfg['Servers'][$i]['host'] = '127.0.0.1';
The default password for "root" user is empty "" do not type anything for the password
If it does not allow empty password you need to edit config.inc.php again and change:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
The problem is a combination of config settings and MySQL not running. This was what helped me to fix this error.
final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
matcher.find();
System.out.println(matcher.group(1));
If nobody has pulled your remote repo yet, you can change your branch HEAD and force push it to said remote repo:
git reset --hard HEAD^
git push -f
(or, if you have direct access to the remote repo, you can change its HEAD reference even though it is a bare repo)
Note, as commented by alien-technology in the comments below, on Windows (CMD session), you would need ^^
:
git reset --hard HEAD^^
git push -f
Update since 2011:
Using git push --force-with-lease
(that I present here, introduced in 2013 with Git 1.8.5) is safer.
See Schwern's answer for illustration.
What if somebody has already pulled the repo? What would I do then?
Then I would suggest something that doesn't rewrite the history:
git revert
locally your last commit (creating a new commit that reverses what the previous commit did)git revert
.1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
'*' works as a modifier for the previous item. So 'abc*def' searches for 'ab' followed by 0 or more 'c's follwed by 'def'.
What you probably want is 'abc.*def' which searches for 'abc' followed by any number of characters, follwed by 'def'.
Try this:
Update users
Set username = 'Jack', password='123'
Where ID = '1'
Or if you're actually trying to insert:
Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:
Bill Venners: Java has four access levels. The default is package. I have always wondered if making package access default was convenient because the three keywords that people from C++ already knew about were private, protected, and public. Or if you had some particular reason that you felt package access should be the default.
James Gosling: A package is generally a set of things that are kind of written together. So generically I could have done one of two things. One was force you always to put in a keyword that gives you the domain. Or I could have had a default value. And then the question is, what makes a sensible default? And I tend to go for what is the least dangerous thing.
So public would have been a really bad thing to make the default. Private would probably have been a bad thing to make a default, if only because people actually don't write private methods that often. And same thing with protected. And in looking at a bunch of code that I had, I decided that the most common thing that was reasonably safe was in the package. And C++ didn't have a keyword for that, because they didn't have a notion of packages.
But I liked it rather than the friends notion, because with friends you kind of have to enumerate who all of your friends are, and so if you add a new class to a package, then you generally end up having to go to all of the classes in that package and update their friends, which I had always found to be a complete pain in the butt.
But the friends list itself causes sort of a versioning problem. And so there was this notion of a friendly class. And the nice thing that I was making that the default -- I'll solve the problem so what should the keyword be?
For a while there actually was a friendly keyword. But because all the others start with "P," it was "phriendly" with a "PH." But that was only in there for maybe a day.
The only way not to capture something is using look-around assertions:
(?<=123-)((apple|banana)(?=-456)|(?=456))
Because even with non-capturing groups (?:…)
the whole regular expression captures their matched contents. But this regular expression matches only apple
or banana
if it’s preceded by 123-
and followed by -456
, or it matches the empty string if it’s preceded by 123-
and followed by 456
.
|Lookaround | Name | What it Does |
-----------------------------------------------------------------------
|(?=foo) | Lookahead | Asserts that what immediately FOLLOWS the |
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?<=foo) | Lookbehind | Asserts that what immediately PRECEDES the|
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?!foo) | Negative | Asserts that what immediately FOLLOWS the |
| | Lookahead | current position in the string is NOT foo|
-------------------------------------------------------------------------
|(?<!foo) | Negative | Asserts that what immediately PRECEDES the|
| | Lookbehind | current position in the string is NOT foo|
-------------------------------------------------------------------------
The accepted answer works but leaves an empty style
attribute on the DOM in my tests. No big deal, but this removes it all:
removeAttr( 'style' );
This assumes you want to remove all dynamic styling and return back to the stylesheet styling.
For a developer who understands the reason it exists but needs to access an API that doesn't handle OPTIONS calls without auth, I need a temporary answer so I can develop locally until the API owner adds proper SPA CORS support or I get a proxy API up and running.
I found you can disable CORS in Safari and Chrome on a Mac.
Disable same origin policy in Chrome
Chrome: Quit Chrome, open an terminal and paste this command: open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir
Safari: Disabling same-origin policy in Safari
If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.
You can do execute this command : rails g migration rename_{old_table_name}to{new_table_name}
after you edit the file and add this code in the method change
rename_table :{old_table_name}, :{new_table_name}
HTML:
<div id="log"></div>
JS:
document.getElementById("log").innerHTML="WHATEVER YOU WANT...";
Simply return with the 'flag' that you want to be treated without using any additional user function. The Controller:
return \Redirect::back()->withSuccess( 'Message you want show in View' );
Notice that I used the 'Success' flag.
The View:
@if( Session::has( 'success' ))
{{ Session::get( 'success' ) }}
@elseif( Session::has( 'warning' ))
{{ Session::get( 'warning' ) }} <!-- here to 'withWarning()' -->
@endif
Yes, it really works!
You need to use javaScript's parseInt()
method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".
zsh has a builtin command emulate
which can emulate different shells by setting the appropriate options, although csh will never be fully emulated.
emulate bash
perform commands
emulate -R zsh
The -R flag restores all the options to their default values for that shell.
See: zsh manual
Just have something like this where you traverse till the given position and then insert:
void addNodeAtPos(int data, int pos)
{
Node* prev = new Node();
Node* curr = new Node();
Node* newNode = new Node();
newNode->data = data;
int tempPos = 0; // Traverses through the list
curr = head; // Initialize current to head;
if(head != NULL)
{
while(curr->next != NULL && tempPos != pos)
{
prev = curr;
curr = curr->next;
tempPos++;
}
if(pos==0)
{
cout << "Adding at Head! " << endl;
// Call function to addNode from head;
}
else if(curr->next == NULL && pos == tempPos+1)
{
cout << "Adding at Tail! " << endl;
// Call function to addNode at tail;
}
else if(pos > tempPos+1)
cout << " Position is out of bounds " << endl;
//Position not valid
else
{
prev->next = newNode;
newNode->next = curr;
cout << "Node added at position: " << pos << endl;
}
}
else
{
head = newNode;
newNode->next=NULL;
cout << "Added at head as list is empty! " << endl;
}
}
This is not the solution to you, but if you want to restrict the function calls to some specific parameter types then you must use the PROATOR { The Python Function prototype validator }. you can refer the following link. https://github.com/mohit-thakur-721/proator
simple one:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
if you have many STRINGS to Concatenate, you should use NSMutableString
for better performance
I'd also consider using a plain old <rect>
which provides the rx
and ry
attributes
MDN SVG docs <- note the second drawn rect element
The best way to boost up android studio runtime performance is to use SSD Drive. It will boost the performance as very much. I did all the above things and felt I should go for new laptop, but suddenly I came to know about SSD Drive and I tried it. Its Much Much better.....
You can use extensions for this.
extension NSDate {
//NSString to NSDate
convenience
init(dateString:String) {
let nsDateFormatter = NSDateFormatter()
nsDateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
// Add the locale if required here
let dateObj = nsDateFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:dateObj!)
}
//NSDate to time string
func getTime() -> String {
let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "hh:mm"
//Can also set the default styles for date or time using .timeStyle or .dateStyle
return timeFormatter.stringFromDate(self)
}
//NSDate to date string
func getDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMM"
return dateFormatter.stringFromDate(self)
}
//NSDate to String
func getString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
return dateFormatter.stringFromDate(self)
}
}
So while execution actual code will look like follows
var dateObjFromString = NSDate(dateString: cutDateTime)
var dateString = dateObjFromString.getDate()
var timeString = dateObjFromString.getTime()
var stringFromDate = dateObjFromString.getString()
There are some defaults methods as well but I guess it might not work for the format you have given from documentation
-dateFromString(_:)
-stringFromDate(_:)
-localizedStringFromDate(_ date: NSDate,
dateStyle dateStyle: NSDateFormatterStyle,
timeStyle timeStyle: NSDateFormatterStyle) -> String
Consider Google Collections for an updated Collections framework that supports generics.
UPDATE: The google collections library is now deprecated. You should use the latest release of Guava instead. It still has all the same extensions to the collections framework including a mechanism for filtering based on a predicate.
OK processing a good amount of data and the output was OK, but had one junk line.
If I piped the output of the script to:
| sed -i '$ d' I would get the following error and finally no output at all sed: no input files
But | head -n -1 worked!
Here is an extension for Swift 4.1 and Xcode 9.4.1:
extension UIAlertController{
func addColorInTitleAndMessage(color:UIColor,titleFontSize:CGFloat = 18, messageFontSize:CGFloat = 13){
let attributesTitle = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: titleFontSize)]
let attributesMessage = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: UIFont.systemFont(ofSize: messageFontSize)]
let attributedTitleText = NSAttributedString(string: self.title ?? "", attributes: attributesTitle)
let attributedMessageText = NSAttributedString(string: self.message ?? "", attributes: attributesMessage)
self.setValue(attributedTitleText, forKey: "attributedTitle")
self.setValue(attributedMessageText, forKey: "attributedMessage")
}}
Cake supports AssemblyInfo files patching. With cake in hands you have infinite ways to implement automatic version incrementing.
Simple example of incrementing version like C# compiler does:
Setup(() =>
{
// Executed BEFORE the first task.
var datetimeNow = DateTime.Now;
var daysPart = (datetimeNow - new DateTime(2000, 1, 1)).Days;
var secondsPart = (long)datetimeNow.TimeOfDay.TotalSeconds/2;
var assemblyInfo = new AssemblyInfoSettings
{
Version = "3.0.0.0",
FileVersion = string.Format("3.0.{0}.{1}", daysPart, secondsPart)
};
CreateAssemblyInfo("MyProject/Properties/AssemblyInfo.cs", assemblyInfo);
});
Here:
Note that you can patch not only versions but also all other necessary information.
If you want to post an array you must use another notation:
foreach ($postvalue as $value){
<input type="hidden" name="result[]" value="$value.">
}
in this way you have three input fields with the name result[] and when posted $_POST['result']
will be an array
We can change context root path using a simple entry in the properties file.
application.properties
### Spring boot 1.x #########
server.contextPath=/ClientApp
### Spring boot 2.x #########
server.servlet.context-path=/ClientApp
If you really want to use String:
NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];
But I would recommend using NSNumber:
NSNumber *number = [[NSNumber alloc] initWithInt:123];
Then just add it to the array.
[array addObject:number];
Don't forget to release it after that, since you created it above.
[number release];
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm
argument can be queried for its tm_wday
member on systems that modify those fields automatically (e.g. some glibc implementations).
int get_weekday(char * str) {
struct tm tm;
memset((void *) &tm, 0, sizeof(tm));
if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
time_t t = mktime(&tm);
if (t >= 0) {
return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc.
}
}
return -1;
}
Or you could encode these rules to do some arithmetic in a really long single line:
EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).
As far as eval vs. global variable solutions...
I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.
var tempNamespace = {};
var myString = "myVarProperty";
tempNamespace[myString] = 5;
Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)
I may be wrong but those who recommend changing
config.assets.compile = true
The comment on this line reads: #Do not fallback to assets pipeline if a precompiled asset is missed.
This suggests that by setting this to true you are not fixing the problem but rather bypassing it and running the pipeline every time. This must surely kill your performance and defeat the purpose of the pipeline?
I had this same error and it was due to the application running in a sub folder that rails didn't know about.
So my css file where in home/subfolder/app/public/.... but rails was looking in home/app/public/...
try either moving your app out of the subfolder or telling rails that it is in a subfolder.
NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.
As of jQuery 1.2.6 you can use one of the core CSS functions, height
and width
(or outerHeight
and outerWidth
, as appropriate).
var height = $("#myDiv").height();
var width = $("#myDiv").width();
var docHeight = $(document).height();
var docWidth = $(document).width();
If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:
import requests
...
def application(environ, start_response):
cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
response_headers = [('Content-type', 'text/plain')]
response_headers.append(('Set-Cookie',cookie))
...
return [bytes(post_env),response_headers]
I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.
Try this sed
version:
ls -l | sed '2 ! d'
It says "delete all the lines that aren't the second one".
FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.
main.c has a main wrapper like this:
#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
// the true main() routine.
}
spi.c, serial.c and usb.c have main wrappers for their respective test code like this:
#ifdef TEST_USB
int main(int argc, char *argv[]) {
// the main() routine for testing the usb code.
}
config.h Which is included by all the c files has an entry like this:
// Uncomment below to test the serial
//#define TEST_SERIAL
// Uncomment below to test the spi code
//#define TEST_SPI
// Uncomment below to test the usb code
#define TEST_USB
use git pull https://github.com/username/repository
It's because the Github and remote repositories aren't in sync. If you pull
the repo and then Push
everything will be in sync and error will go away.
`
To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.
A brief excerpt:
The flag -XX:+PrintGC
(or the alias -verbose:gc
) activates the “simple” GC logging mode
By default the GC log is written to stdout. With -Xloggc:<file>
we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC
and -XX:+PrintGCTimeStamps
as well.
If we use -XX:+PrintGCDetails
instead of -XX:+PrintGC
, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.
With -XX:+PrintGCTimeStamps
a timestamp reflecting the real time passed in seconds since JVM start is added to every line.
If we specify -XX:+PrintGCDateStamps
each line starts with the absolute date and time.
#!/bin/sh
FILE="/path/to/file"
/bin/cat <<EOM >$FILE
text1
text2 # This comment will be inside of the file.
The keyword EOM can be any text, but it must start the line and be alone.
EOM # This will be also inside of the file, see the space in front of EOM.
EOM # No comments and spaces around here, or it will not work.
text4
EOM
You should use the "radix" parameter of the "parseInt" function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt
parseInt('015', 10) => 15
if you don't use it, some javascript engine might use it as an octal parseInt('015') => 0
Embed the video player and use CSS to hide the video. If you do it properly you may even be able to hide only the video and not the controls below it.
However, I'd recommend against it, because it will be a violation of YouTube TOS. Use your own server instead if you really want to play only audio.
Just for completeness, here's a variant that uses print()
(works on Python 2.6-3.x):
from __future__ import print_function
try: from cStringIO import StringIO
except ImportError:
from io import StringIO
def to_int(nums, _s = StringIO()):
print(*nums, sep='', end='', file=_s)
s = _s.getvalue()
_s.truncate(0)
return int(s)
I've measured performance of @cdleary's functions. The results are slightly different.
Each function tested with the input list generated by:
def randrange1_10(digit_count): # same as @cdleary
return [random.randrange(1, 10) for i in xrange(digit_count)]
You may supply your own function via --sequence-creator=yourmodule.yourfunction
command-line argument (see below).
The fastest functions for a given number of integers in a list (len(nums) == digit_count
) are:
len(nums)
in 1..30
def _accumulator(nums):
tot = 0
for num in nums:
tot *= 10
tot += num
return tot
len(nums)
in 30..1000
def _map(nums):
return int(''.join(map(str, nums)))
def _imap(nums):
return int(''.join(imap(str, nums)))
|------------------------------+-------------------|
| Fitting polynom | Function |
|------------------------------+-------------------|
| 1.00 log2(N) + 1.25e-015 | N |
| 2.00 log2(N) + 5.31e-018 | N*N |
| 1.19 log2(N) + 1.116 | N*log2(N) |
| 1.37 log2(N) + 2.232 | N*log2(N)*log2(N) |
|------------------------------+-------------------|
| 1.21 log2(N) + 0.063 | _interpolation |
| 1.24 log2(N) - 0.610 | _genexp |
| 1.25 log2(N) - 0.968 | _imap |
| 1.30 log2(N) - 1.917 | _map |
To plot the first figure download cdleary.py
and make-figures.py
and run (numpy
and matplotlib
must be installed to plot):
$ python cdleary.py
Or
$ python make-figures.py --sort-function=cdleary._map \
> --sort-function=cdleary._imap \
> --sort-function=cdleary._interpolation \
> --sort-function=cdleary._genexp --sort-function=cdleary._sum \
> --sort-function=cdleary._reduce --sort-function=cdleary._builtins \
> --sort-function=cdleary._accumulator \
> --sequence-creator=cdleary.randrange1_10 --maxn=1000
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
.gitignore
is a text file comprising a list of files in your directory that git will ignore or not add/update in the repository.
.gitkeep
Since Git removes or doesn't add empty directories to a repository, .gitkeep is sort of a hack (I don't think it's officially named as a part of Git) to keep empty directories in the repository.
Just do a touch /path/to/emptydirectory/.gitkeep
to add the file, and Git will now be able to maintain this directory in the repository.
you can just use
ls > filenames.txt
(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd
to go to that folder first, or you can ls ~/docs > filenames.txt
Using org.apache.commons.lang.StringUtils
makes it very simple.
capitalizeStr = StringUtils.capitalize(str);
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
function getTodaysTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const startOfDay = currentTimeStamp - (currentTimeStamp % 86400);_x000D_
return { startOfDay, endOfDay: startOfDay + 86400 - 1 };_x000D_
}_x000D_
_x000D_
// starts from sunday_x000D_
function getThisWeeksTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const currentDay = new Date(currentTimeStamp * 1000);_x000D_
const startOfWeek = currentTimeStamp - (currentDay.getDay() * 86400) - (currentTimeStamp % 86400);_x000D_
return { startOfWeek, endOfWeek: startOfWeek + 7 * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
function getThisMonthsTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const currentDay = new Date(currentTimeStamp * 1000);_x000D_
const startOfMonth = currentTimeStamp - ((currentDay.getDate() - 1) * 86400) - (currentTimeStamp % 86400);_x000D_
const currentMonth = currentDay.getMonth() + 1;_x000D_
let daysInMonth = 0;_x000D_
if (currentMonth === 2) daysInMonth = 28;_x000D_
else if ([1, 3, 5, 7, 8, 10, 12].includes(currentMonth)) daysInMonth = 31;_x000D_
else daysInMonth = 30;_x000D_
return { startOfMonth, endOfMonth: startOfMonth + daysInMonth * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
console.log(getTodaysTimeStamp());_x000D_
console.log(getThisWeeksTimeStamp());_x000D_
console.log(getThisMonthsTimeStamp());
_x000D_
You can get really fine timing (seconds.parts of seconds) using this StopWatch class. It uses the high-precision timer in the iPhone. Using NSDate will only get you second(s) accuracy. This version is designed specifically for autorelease and objective-c. I have a c++ version as well if needed. You can find the c++ version here.
StopWatch.h
#import <Foundation/Foundation.h>
@interface StopWatch : NSObject
{
uint64_t _start;
uint64_t _stop;
uint64_t _elapsed;
}
-(void) Start;
-(void) Stop;
-(void) StopWithContext:(NSString*) context;
-(double) seconds;
-(NSString*) description;
+(StopWatch*) stopWatch;
-(StopWatch*) init;
@end
StopWatch.m
#import "StopWatch.h"
#include <mach/mach_time.h>
@implementation StopWatch
-(void) Start
{
_stop = 0;
_elapsed = 0;
_start = mach_absolute_time();
}
-(void) Stop
{
_stop = mach_absolute_time();
if(_stop > _start)
{
_elapsed = _stop - _start;
}
else
{
_elapsed = 0;
}
_start = mach_absolute_time();
}
-(void) StopWithContext:(NSString*) context
{
_stop = mach_absolute_time();
if(_stop > _start)
{
_elapsed = _stop - _start;
}
else
{
_elapsed = 0;
}
NSLog([NSString stringWithFormat:@"[%@] Stopped at %f",context,[self seconds]]);
_start = mach_absolute_time();
}
-(double) seconds
{
if(_elapsed > 0)
{
uint64_t elapsedTimeNano = 0;
mach_timebase_info_data_t timeBaseInfo;
mach_timebase_info(&timeBaseInfo);
elapsedTimeNano = _elapsed * timeBaseInfo.numer / timeBaseInfo.denom;
double elapsedSeconds = elapsedTimeNano * 1.0E-9;
return elapsedSeconds;
}
return 0.0;
}
-(NSString*) description
{
return [NSString stringWithFormat:@"%f secs.",[self seconds]];
}
+(StopWatch*) stopWatch
{
StopWatch* obj = [[[StopWatch alloc] init] autorelease];
return obj;
}
-(StopWatch*) init
{
[super init];
return self;
}
@end
The class has a static stopWatch
method that returns an autoreleased object.
Once you call start
, use the seconds
method to get the elapsed time. Call start
again to restart it. Or stop
to stop it. You can still read the time (call seconds
) anytime after calling stop
.
Example In A Function (Timing call of execution)
-(void)SomeFunc
{
StopWatch* stopWatch = [StopWatch stopWatch];
[stopWatch Start];
... do stuff
[stopWatch StopWithContext:[NSString stringWithFormat:@"Created %d Records",[records count]]];
}
Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.
Best and shortest way in my opinion for onchange events on the dropdown to get the selected option:
$('option:selected',this);
to get the value attribute:
$('option:selected',this).attr('value');
to get the shown part between the tags:
$('option:selected',this).text();
In your sample:
$("#select-id").change(function(){
var cur_value = $('option:selected',this).text();
});
You might also consider running the (non-python) program xls2csv. Feed it an xls file, and you should get back a csv.
I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.
.divtagABS {
width: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
}
Basically, you use left: 50%, then back it out half of it's width with a negative margin.
Step-by-step:
use-gulp
which
uses(require
s) node_modules
like gulp
and gulp-util
.gulp-util
lib and test it locally with your use-gulp
project... gulp-util
project on github\bitbucket etc.cd use-gulp/node_modules
gulp-util
as gulp-util-dev
: git clone https://.../gulp-util.git gulp-util-dev
npm install
to ensure dependencies of gulp-util-dev
are available.gulp-util
as gulp-util-dev
. In your use-gulp
project, you can now replace: require('gulp-util')...;
call with : require('gulp-util-dev')
to test your changes you made to gulp-util-dev
One could use an additional hidden input element with the same name and value as that of the disabled list. This will ensure that the value is passed in $_POST variables.
Eg:
<select name="sel" disabled><option>123</select>_x000D_
<input type="hidden" name="sel" value=123>
_x000D_
ln -s source_file target_file
For those that might end up here looking for the opposite conversion (from XMLGregorianCalendar
to Date
):
XMLGregorianCalendar xcal = <assume this is initialized>;
java.util.Date dt = xcal.toGregorianCalendar().getTime();
Here's why:
char x;
char *y=malloc(1);
char *z=alloca(&x-y);
*z = 1;
Not that anyone would write this code, but the size argument you're passing to alloca
almost certainly comes from some sort of input, which could maliciously aim to get your program to alloca
something huge like that. After all, if the size isn't based on input or doesn't have the possibility to be large, why didn't you just declare a small, fixed-size local buffer?
Virtually all code using alloca
and/or C99 vlas has serious bugs which will lead to crashes (if you're lucky) or privilege compromise (if you're not so lucky).
What you need are character classes. In that, you've only to worry about the ]
, \
and -
characters (and ^
if you're placing it straight after the beginning of the character class "[
" ).
Syntax: [
characters]
where characters is a list with characters.
Example:
var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");
You can do:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]
plt.plot(x, y, style='.-')
plt.show()
This will return a graph with the data points marked with a dot
The top border of frame is of size 30.You can write code for printing the coordinate of any point on the frame using MouseInputAdapter.You will find when the cursor is just below the top border of the frame the y coordinate is not zero , its close to 30.Hence if you give size to frame 300 * 300 , the size available for putting the components on the frame is only 300 * 270.So if you need to have size 300 * 300 ,give 300 * 330 size of the frame.
Years ago MSIE 5 or 5.5 (and probably both) had some serious issue with a "-" in the HTML block if you can believe it. Alhough it's not directly related, ever since we've stored an MD5 hash (containing letters and numbers only) in the cookie to look up everything else in server-side database.
I was having the exact same error. After some hours, I noticed that there was an extra comma in my .JSON file, on the very last key-value pair.
//doesn't work
{
"key":"value",
"key":"value",
"key":"value",
}
Then I just took it off (the last ',') and that solved the problem.
//works
{
"key":"value",
"key":"value",
"key":"value"
}
One way to handle String manipulations is StringUtils from Apache commons.
String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);
You can find it here. commons-lang includes lots more and is well supported.
It looks like you're having more trouble with Validation than errors/exceptions so I'll say a bit about both.
Validation
Controller actions should generally take Input Models where the validation is declared directly on the model.
public class Customer
{
[Require]
public string Name { get; set; }
}
Then you can use an ActionFilter
that automatically sends validation messages back to the client.
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid) {
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
For more information about this check out http://ben.onfabrik.com/posts/automatic-modelstate-validation-in-aspnet-mvc
Error handling
It's best to return a message back to the client that represents the exception that happened (with relevant status code).
Out of the box you have to use Request.CreateErrorResponse(HttpStatusCode, message)
if you want to specify a message. However, this ties the code to the Request
object, which you shouldn't need to do.
I usually create my own type of "safe" exception that I expect the client would know how to handle and wrap all others with a generic 500 error.
Using an action filter to handle the exceptions would look like this:
public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var exception = context.Exception as ApiException;
if (exception != null) {
context.Response = context.Request.CreateErrorResponse(exception.StatusCode, exception.Message);
}
}
}
Then you can register it globally.
GlobalConfiguration.Configuration.Filters.Add(new ApiExceptionFilterAttribute());
This is my custom exception type.
using System;
using System.Net;
namespace WebApi
{
public class ApiException : Exception
{
private readonly HttpStatusCode statusCode;
public ApiException (HttpStatusCode statusCode, string message, Exception ex)
: base(message, ex)
{
this.statusCode = statusCode;
}
public ApiException (HttpStatusCode statusCode, string message)
: base(message)
{
this.statusCode = statusCode;
}
public ApiException (HttpStatusCode statusCode)
{
this.statusCode = statusCode;
}
public HttpStatusCode StatusCode
{
get { return this.statusCode; }
}
}
}
An example exception that my API can throw.
public class NotAuthenticatedException : ApiException
{
public NotAuthenticatedException()
: base(HttpStatusCode.Forbidden)
{
}
}
I think one of the Advantages of code first is that you can back up all the changes you've made to a version control system like Git. Because all your tables and relationships are stored in what are essentially just classes, you can go back in time and see what the structure of your database was before.
It means that objects should only have as many dependencies as is needed to do their job and the dependencies should be few. Furthermore, an object’s dependencies should be on interfaces and not on “concrete” objects, when possible. (A concrete object is any object created with the keyword new.) Loose coupling promotes greater reusability, easier maintainability, and allows you to easily provide “mock” objects in place of expensive services.
The “Dependency Injection” (DI) is also known as “Inversion of Control” (IoC), can be used as a technique for encouraging this loose coupling.
There are two primary approaches to implementing DI:
It’s the technique of passing objects dependencies to its constructor.
Note that the constructor accepts an interface and not concrete object. Also, note that an exception is thrown if the orderDao parameter is null. This emphasizes the importance of receiving a valid dependency. Constructor Injection is, in my opinion, the preferred mechanism for giving an object its dependencies. It is clear to the developer while invoking the object which dependencies need to be given to the “Person” object for proper execution.
But consider the following example… Suppose you have a class with ten methods that have no dependencies, but you’re adding a new method that does have a dependency on IDAO. You could change the constructor to use Constructor Injection, but this may force you to changes to all constructor calls all over the place. Alternatively, you could just add a new constructor that takes the dependency, but then how does a developer easily know when to use one constructor over the other. Finally, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? “Setter Injection” is another DI technique that can be used in situations such as this.
Setter Injection does not force dependencies to be passed to the constructor. Instead, the dependencies are set onto public properties exposed by the object in need. As implied previously, the primary motivators for doing this include:
Here is the example of how the above code would look like:
public class Person {
public Person() {}
public IDAO Address {
set { addressdao = value; }
get {
if (addressdao == null)
throw new MemberAccessException("addressdao" +
" has not been initialized");
return addressdao;
}
}
public Address GetAddress() {
// ... code that uses the addressdao object
// to fetch address details from the datasource ...
}
// Should not be called directly;
// use the public property instead
private IDAO addressdao;
Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.
You need to detect the OS your program is running on, then:
For Linux -
import subprocess
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)
For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html
More resources:
Print PDF document with python's win32print module?
How do I print to the OS's default printer in Python 3 (cross platform)?
From your command line you can run..
php -i
I know it's not the browser window, but you can't see the phpinfo();
contents without making the function call. Obviously, the best approach would be to have a phpinfo script in the root of your web server directory, that way you have access to it at all times via http://localhost/info.php
or something similar (NOTE: don't do this in a production environment or somewhere that is publicly accessible)
EDIT: As mentioned by binaryLV, its quite common to have two versions of a php.ini per installation. One for the command line interface (CLI) and the other for the web server interface. If you want to see phpinfo output for your web server make sure you specify the ini file path, for example...
php -c /etc/php/apache2/php.ini -i
Below is an example of a method in a Java controller.
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel)
{
return HttpStatus.OK;
}
By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.
Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):
POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object
... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--
NOTE: each boundary string must be prefixed with an extra --
, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.
Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.
In the example above, you can see the input MAX_FILE_SIZE
with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition
header.
The full details are here.
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
For thoses Who are using spring-boot and jdbc for connection. You have to be careful while writing jdbcUrl in application.properties
With SID in Database connection -
source.datasource.jdbcUrl = jdbc:oracle:thin:@[HOST][:PORT]:SID
With Service name in db connection
globe.datasource.jdbcUrl = jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE
This worked for me :)
the correct way to do will be as following in the old-style classes which doesn't inherit from 'object'
class A:
def foo(self):
return "Hi there"
class B(A):
def foo(self, name):
return A.foo(self) + name
Why not just make the access_token last as long as the refresh_token and not have a refresh_token?
In addition to great answers other people have provided, there is another reason why we would use refresh tokens and it's to do with claims.
Each token contains claims which can include anything from the user's name, their roles, or the provider which created the claim. As a token is refreshed, these claims are updated.
If we refresh the tokens more often, we are obviously putting more strain on our identity services; however, we are getting more accurate and up-to-date claims.
This worked best for me injecting the HTML into the popup such as <body onload="window.print()"...
The above works for IE, Chrome, and FF (on Mac) but no FF on Windows.
https://stackoverflow.com/a/11782214/1322092
var html = '<html><head><title></title>'+
'<link rel="stylesheet" href="css/mycss.css" type="text/css" />'+
'</head><body onload="window.focus(); window.print(); window.close()">'+
data+
'</body></html>';
Set editable
to False
and default
to your default value.
http://docs.djangoproject.com/en/stable/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
Unless I grossly misunderstood your question, move overflow-x:scroll
from .search-table
to .search-table-outter
.
.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto; }
As far as I know you can't give scrollbars to tables themselves.
Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branch
Merge Squash: retains the changes but omits the individual commits from history
Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master
More on here
Example to get the last input element:
document.querySelector(".groups-container >div:last-child input")
Very simple, you close it :)
var myWebSocket = new WebSocket("ws://example.org");
myWebSocket.send("Hello Web Sockets!");
myWebSocket.close();
Did you check also the following site And check the introduction article of Opera
Use CMAKE_PREFIX_PATH by adding multiple paths (separated by semicolons and no white spaces). You can set it as an environmental variable to avoid having absolute paths in your cmake configuration files
Notice that cmake will look for config file in any of the following folders where is any of the path in CMAKE_PREFIX_PATH and name is the name of the library you are looking for
<prefix>/ (W)
<prefix>/(cmake|CMake)/ (W)
<prefix>/<name>*/ (W)
<prefix>/<name>*/(cmake|CMake)/ (W)
<prefix>/(lib/<arch>|lib|share)/cmake/<name>*/ (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/ (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (U)
In your case you need to add to CMAKE_PREFIX_PATH the following two paths:
D:/develop/cmake/libs/libA;D:/develop/cmake/libB
You can use rand($min, $max)
for that exact purpose.
In order to limit the values to values with x digits you can use the following:
$x = 3; // Amount of digits
$min = pow(10,$x);
$max = pow(10,$x+1)-1);
$value = rand($min, $max);
To center align text
input[type='text'] { text-align:center;}
To center align the textbox in the container that it sits in, apply text-align:center to the container.
for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.
Though this question is rather old, here's a answer :)
What you are asking for can be achieved by using jQuery's .click() event method and .on() event method
So this could be the code:
// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");
$(document).ready(function() {
// When the document is ready/loaded, execute function
// Hide hangoutButton
hangoutButton.hide();
// Assign "click"-event-method to userImage
userImage.on("click", function() {
console.log("in onclick");
hangoutButton.click();
});
});
So, if you have a statement something like the following, you're saying that you get no 'print' result?
select * from sysobjects PRINT 'Just selected * from sysobjects'
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like
raiserror ('My Print Statement', 10,1) with nowait
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0;
--> Note that, this is Query Result, a ResultSet. This is exportable to other formats.
And, you can export the Query Result to Text
format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0;
:
"SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"
DESCRIBE <TABLE_NAME>
--> Note: This is script output.
From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:
net start > c:\netstart.txt
You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\
drive.
I think you mean the active state
button:active{
//some styling
}
These are all the possible pseudo states a link can have in CSS:
a:link {color:#FF0000;} /* unvisited link, same as regular 'a' */
a:hover {color:#FF00FF;} /* mouse over link */
a:focus {color:#0000FF;} /* link has focus */
a:active {color:#0000FF;} /* selected link */
a:visited {color:#00FF00;} /* visited link */
See also: http://www.w3.org/TR/selectors/#the-user-action-pseudo-classes-hover-act
Try:
String newValue = String.format("%d", (int)d);
you can use:
$('body').ready(function(){
$(document).on('change', '#elemID', function(){
// do something
});
});
It works with me.
If you want to make sure your android client application is logged out from some server before your Activity gets killed --> log out with a service on its own thread (that's what you're supposed to do anyway).
Disabling the back button won't solve anything for you. You'll still have the same problem when the user receives a phone call for instance. When a phone call is received, your activity has about as much chances of getting killed before it gets a reliable answer back from the network.
That's why you should let a service wait on its own thread for the answer from the network, and then make it try again if it doesn't succeed. The android service is not only much less likely to get killed before it gets an answer back, but should it really get killed before finishing the job, it can always get revived by AlarmManager to try again.
PHP variables are assigned by value, passed to functions by value and when containing/representing objects are passed by reference. You can force variables to pass by reference using an '&'.
Assigned by value/reference example:
$var1 = "test";
$var2 = $var1;
$var2 = "new test";
$var3 = &$var2;
$var3 = "final test";
print ("var1: $var1, var2: $var2, var3: $var3);
output:
var1: test, var2: final test, var3: final test
Passed by value/reference example:
$var1 = "foo";
$var2 = "bar";
changeThem($var1, $var2);
print "var1: $var1, var2: $var2";
function changeThem($var1, &$var2){
$var1 = "FOO";
$var2 = "BAR";
}
output:
var1: foo, var2 BAR
Object variables passed by reference example:
class Foo{
public $var1;
function __construct(){
$this->var1 = "foo";
}
public function printFoo(){
print $this->var1;
}
}
$foo = new Foo();
changeFoo($foo);
$foo->printFoo();
function changeFoo($foo){
$foo->var1 = "FOO";
}
output:
FOO
(The last example could be better probably.)
I suggest to use autotools
:
//##
Place generated object files (.o) into the same directory as their source files, in order to avoid collisions when non-recursive make is used.
AUTOMAKE_OPTIONS = subdir-objects
just including it in Makefile.am
with the other quite simple stuff.
Here is the tutorial.
I went through all answers, but doesn't satisfied my exact needed answer, so here is an example that I wrote and perfectly works, even user clicks the Don't ask again checkbox.
Create a method that will be called when you want to ask for runtime permission like readContacts()
or you can also have openCamera()
as shown below:
private void readContacts() {
if (!askContactsPermission()) {
return;
} else {
queryContacts();
} }
Now we need to make askContactsPermission()
, you can also name it as askCameraPermission()
or whatever permission you are going to ask.
private boolean askContactsPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(parentLayout, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
}).show();
} else if (contactPermissionNotGiven) {
openPermissionSettingDialog();
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
contactPermissionNotGiven = true;
}
return false;
}
Before writing this function make sure you have defined the below instance variable as shown:
private View parentLayout;
private boolean contactPermissionNotGiven;;
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
Now final step to override the onRequestPermissionsResult
method as shown below:
/**
* Callback received when a permissions request has been completed.
*/
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
queryContacts();
}
}
}
Here we are done with the RunTime permissions, the addon is the openPermissionSettingDialog()
which simply open the Setting screen if user have permanently disable the permission by clicking Don't ask again checkbox. below is the method:
private void openPermissionSettingDialog() {
String message = getString(R.string.message_permission_disabled);
AlertDialog alertDialog =
new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
.setMessage(message)
.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
dialog.cancel();
}
}).show();
alertDialog.setCanceledOnTouchOutside(true);
}
What we missed ?
1. Defining the used strings in strings.xml
<string name="permission_rationale">"Contacts permissions are needed to display Contacts."</string>_x000D_
<string name="message_permission_disabled">You have disabled the permissions permanently,_x000D_
To enable the permissions please go to Settings -> Permissions and enable the required Permissions,_x000D_
pressing OK you will be navigated to Settings screen</string>
_x000D_
Initializing the parentLayout
variable inside onCreate
method
parentLayout = findViewById(R.id.content);
Defining the required permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
_x000D_
The queryContacts
method, based on your need or the runtime permission you can call your method before which the permission
was needed. in my case I simply use the loader to fetch the contact as shown below:
private void queryContacts() {
getLoaderManager().initLoader(0, null, this);}
This works great happy coding :)
new JwtSecurityTokenHandler().ReadToken("")
will return a SecurityToken
new JwtSecurityTokenHandler().ReadJwtToken("")
will return a JwtSecurityToken
If you just change the method you are using you can avoid the cast in the above answer
From your screenshot it appears you have ReSharper installed.
Depending on the key binding options you chose when you installed it, some of your standard shortcuts may now be redirected to ReSharper commands. It's worth checking, for example Ctrl+E, C is used by R# for the code cleanup dialog.
If you want vertical sizing proportional to a width set in pixels on an enclosing div, I believe you need an extra element, like so:
#html
<div class="ptest">
<div class="ptest-wrap">
<div class="ptest-inner">
Put content here
</div>
</div>
</div>
#css
.ptest {
width: 200px;
position: relative;
}
.ptest-wrap {
padding-top: 60%;
}
.ptest-inner {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #333;
}
Here's the 2 div solution that doesn't work. Note the 60% vertical padding is proportional to the window width, not the div.ptest
width:
Here's the example with the code above, which does work:
In addition to @millimoose's answer, setters can also be used to update other values.
function Name(first, last) {
this.first = first;
this.last = last;
}
Name.prototype = {
get fullName() {
return this.first + " " + this.last;
},
set fullName(name) {
var names = name.split(" ");
this.first = names[0];
this.last = names[1];
}
};
Now, you can set fullName
, and first
and last
will be updated and vice versa.
n = new Name('Claude', 'Monet')
n.first # "Claude"
n.last # "Monet"
n.fullName # "Claude Monet"
n.fullName = "Gustav Klimt"
n.first # "Gustav"
n.last # "Klimt"
I had the same problem while designing a template in Mailjet. Solution of the problem was minified CSS code inside <style>
tags.
You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this
import numpy
from matplotlib import pyplot
x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
ax.annotate(str(j),xy=(i,j))
pyplot.show()
If you want the annotations offset a little, you could change the annotate
line to something like
ax.annotate(str(j),xy=(i,j+0.5))
Like all OO languages, Groovy has no concept of "global" by itself (unlike, say, BASIC, Python or Perl).
If you have several methods that need to share the same variable, use a field:
class Foo {
def a;
def foo() {
a = 1;
}
def bar() {
print a;
}
}
You can also use
:-0
This sets the cursor at the present line (blank here) at the 0 column.
As mentioned in Scott Kuhl's answer this issue is mentioned in https://github.com/madskristensen/WebCompiler/issues/413
For me, running the command npm i caniuse-lite- browserslist
only worked for about 1/2 a day before it was an issue again.
The following solution, mentioned in the post, works much better. This updates the node.js file so that it uses console.log
instead of console.warn
when returning these errors.
You can manually update this file located at C:\Users\[Username]\AppData\Local\Temp\WebCompiler[VersionNumber]\node_modules\browserslist
Or, so that it is done automatically, add the following to your .csproj file by:
</Project>
end tag and before the build web compiler package was imported. <ItemGroup>
<PackageReference Include="MSBuildTasks" Version="1.5.0.235">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<TempFolder>$([System.IO.Path]::GetTempPath())</TempFolder>
</PropertyGroup>
<ItemGroup>
<BrowsersListNodeJsFiles Include="$(TempFolder)\WebCompiler*\node_modules\browserslist\node.js" />
</ItemGroup>
<Target Name="BrowsersListWarningsAsInfo" BeforeTargets="WebCompile">
<FileUpdate Files="@(BrowsersListNodeJsFiles)"
Regex="console.warn"
ReplacementText="console.log" />
</Target>
One thing the top voted answer did not mention was that you need single quotes, 'like this', around your search value if it is a text value like so:
public boolean checkIfMyTitleExists(String title) {
String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
Cursor cursor = database.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Otherwise, you will get a "SQL(query) error or missing database" error like I did without the single quotes around the title field.
If it is a numeric value, it does not need single quotes.
Refer to this SQL post for more details
You can use the following CSS to style the input element.
input[type="date"] {_x000D_
background-color: red;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
font-size: 18px;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
Solr currently checks for a "pure negative" query and inserts *:*
(which matches all documents) so that it works correctly.
-foo
is transformed by solr into (*:* -foo)
The big caveat is that Solr only checks to see if the top level query is a pure negative query!
So this means that a query like bar OR (-foo)
is not changed since the pure negative query is in a sub-clause of the top level query. You need to transform this query yourself into bar OR (*:* -foo)
You may check the solr query explanation to verify the query transformation:
?q=-title:foo&debug=query
is transformed to
(+(-title:foo +MatchAllDocsQuery(*:*))
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.You can also use PostCSS and the custom selectors plugin
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
article :--headings {
margin-top: 0;
}
Output:
article h1,
article h2,
article h3,
article h4,
article h5,
article h6 {
margin-top: 0;
}
A .
in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.
search for terminal after opening the termincal type
su <admin-user-name> //su - switch user
enter and then give the admin password then run your sudo commands e.g:
sudo open MySQLWorkbench.app
With Git 2.23 onwards, one can use git switch <branch name>
to switch branches.
Bash 3 solution:
In reading some of the answers I put together a quick little function I would like to contribute back that might help others.
# Define a hash like this
MYHASH=("firstName:Milan"
"lastName:Adamovsky")
# Function to get value by key
getHashKey()
{
declare -a hash=("${!1}")
local key
local lookup=$2
for key in "${hash[@]}" ; do
KEY=${key%%:*}
VALUE=${key#*:}
if [[ $KEY == $lookup ]]
then
echo $VALUE
fi
done
}
# Function to get a list of all keys
getHashKeys()
{
declare -a hash=("${!1}")
local KEY
local VALUE
local key
local lookup=$2
for key in "${hash[@]}" ; do
KEY=${key%%:*}
VALUE=${key#*:}
keys+="${KEY} "
done
echo $keys
}
# Here we want to get the value of 'lastName'
echo $(getHashKey MYHASH[@] "lastName")
# Here we want to get all keys
echo $(getHashKeys MYHASH[@])
Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.
However, I'm able to grab colors easily in Firefox.
In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)
Scroll Bar is added to the List box automatically unless its visibility is set to Hidden. Whenever the size of List Items exceeds the one, which can be shown inside a list box vertical or horizontal list box can be seen during the run time.
You might be interested in this blog post.
http://seatgeek.com/blog/dev/fuzzywuzzy-fuzzy-string-matching-in-python
Fuzzywuzzy is a Python library that provides easy distance measures such as Levenshtein distance for string matching. It is built on top of difflib in the standard library and will make use of the C implementation Python-levenshtein if available.
Parsing a string with date and time into a particular point in time (Java calls it an "Instant
") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time
and java.time.chrono
, covers almost all needs (except Time Dilation :) ).
However, that complexity brings a lot of confusion.
The key to understand date parsing is:
LocalDateTime
, ZonedDateTime
et al. so complicatedThere are time zones.
A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.
There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."
Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.
To make it a bit more complicated (but that's not too important for your use case) :
2040-12-31 24:00:00
may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.
Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.
Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00
may be off a couple of seconds from the future parsing.
java.util.Date
which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.java.sql.Date
was introduced, with it's own limitations.Calendar
API was introduced.java.time
When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.
Does it contain the date and the time?
Does it have a time offset?
A time offset is the +hh:mm
part. Sometimes, +00:00
may be substituted with Z
as 'Zulu time', UTC
as Universal Time Coordinated, or GMT
as Greenwich Mean Time. These also set the time zone.
For these timestamps, you use OffsetDateTime
.
Does it have a time zone?
For these timestamps, you use ZonedDateTime
.
Zone is specified either by
The list of time zones is compiled by a "TZ database", backed by ICAAN.
According to ZoneId
's javadoc, The zone id's can also somehow be specified as Z
and offset. I'm not sure how this maps to real zones.
If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle
, see below.
If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime
and converted to OffsetDateTime
by adding the missing info:
Duration
), or when you don't know and it doesn't really matter (e.g. local bus schedule).Partial time information
LocalDate
, LocalTime
, OffsetTime
, MonthDay
, Year
, or YearMonth
out of it.If you have the full information, you can get a java.time.Instant
. This is also internally used to convert between OffsetDateTime
and ZonedDateTime
.
There is an extensive documentation on DateTimeFormatter
which can both parse a timestamp string and format to string.
The pre-created DateTimeFormatter
s should cover moreless all standard timestamp formats. For instance, ISO_INSTANT
can parse 2011-12-03T10:15:30.123457Z
.
If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).
private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
.toFormatter();
I recommend to look at the source code of DateTimeFormatter
and get inspired on how to build one using DateTimeFormatterBuilder
. While you're there, also have a look at ResolverStyle
which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.
Now, the frequent mistake is to go into the complexity of TemporalAccessor
. This comes from how the developers were used to work with SimpleDateFormatter.parse(String)
. Right, DateTimeFormatter.parse("...")
gives you TemporalAccessor
.
// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");
But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);
You do not actually need to the DateTimeFormatter
either. The types you want to parse have the parse(String)
methods.
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");
Regarding TemporalAccessor
, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.
I hope I shed some light of understanding onto your soul :)
Note: There's a backport of java.time
to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.
[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )
I faced the same error today, using React with Typescript and a back-end using Java Spring boot, if you have a hand on your back-end you can simply add a configuration file for the CORS.
For the below example I set allowed origin to * to allow all but you can be more specific and only set url like http://localhost:3000.
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class AppCorsConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
I ended up using this code which should work on any open dialogs on the page, ignores clicks on tooltips, and cleans up the resources of the dialog being closed as well.
$(document).mousedown(function(e) {
var clicked = $(e.target); // get the element clicked
if (clicked.is('.ui-dialog-content, .ui-dialog-titlebar, .ui-tooltip') || clicked.parents().is('.ui-dialog-content, .ui-dialog-titlebar, .ui-tooltip')) {
return; // click happened within the dialog, do nothing here
} else { // click was outside the dialog, so close it
$('.ui-dialog-content').dialog("close");
$('.ui-dialog-content').dialog("destroy");
$('.ui-dialog-content').detach();
}
});
a += b
is in this case the same as
a = a + b
In this case cnt += 1 means that cnt is increased by one.
Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.
Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.
You're getting errors 'table liam does not exist' because the table's name is Liam
which is not the same as liam
. MySQL table names are case sensitive.
Copied from bobince answer, but made it support question marks in the query string, eg
http://www.google.com/search?q=test???+something&aq=f
Is it valid to have more than one question mark in a URL?
function removeUrlParameter(url, parameter) {
var urlParts = url.split('?');
if (urlParts.length >= 2) {
// Get first part, and remove from array
var urlBase = urlParts.shift();
// Join it back up
var queryString = urlParts.join('?');
var prefix = encodeURIComponent(parameter) + '=';
var parts = queryString.split(/[&;]/g);
// Reverse iteration as may be destructive
for (var i = parts.length; i-- > 0; ) {
// Idiom for string.startsWith
if (parts[i].lastIndexOf(prefix, 0) !== -1) {
parts.splice(i, 1);
}
}
url = urlBase + '?' + parts.join('&');
}
return url;
}
Have a look at the documentation. Use the intValue
method:
NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
If you want to select the same item in a listbox
using a listview
, you can use:
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
For aa As Integer = 0 To ListView1.SelectedItems.Count - 1
ListBox1.SelectedIndex = ListView1.SelectedIndices(aa)
Next
End Sub
A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.
public class ListModel<T>
{
public List<T> Items { get; set; }
public ListModel(List<T> list) {
Items = list;
}
}
and when you return the View you just need to simply do:
List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));
then define the list in the model:
@model ListModel<customClass>
and ready to go:
@foreach(var element in Model.Items) {
//do as needed...
}
I had the same issue. This is what worked for me.
There are 2 php.ini files:
NOTE: This is using my version of PHP and Apache, change to what yours are.
The php.ini file located in the both folders is what you need to update, the extentions:
These are what you need to uncomment (remove the ; symbol).
Restart both Wamp and the Command Prompt.
Hopefully it will work for you :).
Looking onto this issue Github - Request/Upload progress handling via @angular/http, angular2 http does not support file upload yet.
For very basic file upload I created such service function as a workaround (using ???????'s answer):
uploadFile(file:File):Promise<MyEntity> {
return new Promise((resolve, reject) => {
let xhr:XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(<MyEntity>JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.open('POST', this.getServiceUrl(), true);
let formData = new FormData();
formData.append("file", file, file.name);
xhr.send(formData);
});
}
Just combine them. I think this should work but it's untested:
p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() +
geom_smooth(fill="blue", colour="darkblue", size=1)
p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) +
geom_smooth(data=visual2, fill="red", colour="red", size=1)
print(p)
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.
Here is my solution:
Firstly, import pandas as pd:
import pandas as pd
Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.
df = pd.read_excel('testexcel.xlsx', index_col=0)
At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd
.
For visual inspection, read the dataframe using df.head()
which will print the following output
Now you can fetch the values of the desired columns of the dataframe and print it
EDIT: This answer is correct for version 0.2.10
. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14
.
Another reason to use $state.params
is when you need to extract query parameters like this:
$stateProvider.state('a', {
url: 'path/:id/:anotherParam/?yetAnotherParam',
controller: 'ACtrl',
});
module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam
}
Just change the routeReuseStrategy from the angular Router:
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
Set the routerproperty "navigated" to false:
this._router.navigated = false;
Then navigate to your component:
this._router.navigate(['routeToYourComponent'])
After that reinstate the old/default routeReuseStrategy:
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
You can also make a service out of this:
@Injectable({
providedIn: 'root'
})
export class RouterService {
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
reuseRoutes(reuse: boolean) {
if (!reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
if (reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
async refreshPage(url?: string) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this._router.navigated = false;
url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}