/^(([+]{0,1}\d{2})|\d?)[\s-]?[0-9]{2}[\s-]?[0-9]{3}[\s-]?[0-9]{4}$/gm
Tested for
+94 77 531 2412
+94775312412
077 531 2412
0775312412
77 531 2412
// Not matching
77-53-12412
+94-77-53-12412
077 123 12345
77123 12345
Yes, though you have to turn on TLS 1.2 manually at System.Net.ServicePointManager.SecurityProtocol
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // comparable to modern browsers
var response = WebRequest.Create("https://www.howsmyssl.com/").GetResponse();
var body = new StreamReader(response.GetResponseStream()).ReadToEnd();
Your client is using TLS 1.2, the most modern version of the encryption protocol
Out the box, WebRequest will use TLS 1.0 or SSL 3.
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
You can use %x
or %X
or %p
; all of them are correct.
%x
, the address is given as lowercase, for example: a3bfbc4
%X
, the address is given as uppercase, for example: A3BFBC4
Both of these are correct.
If you use %x
or %X
it's considering six positions for the address, and if you use %p
it's considering eight positions for the address. For example:
The Guideline is invaluable - and the app:layout_constraintGuide_percent is a great friend... However sometimes we want percentages without guidelines. Now it's possible to use weights:
android:layout_width="0dp"
app:layout_constraintHorizontal_weight="1"
Here is a more complete example that uses a guideline with additional weights:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="android.itomerbu.layoutdemo.MainActivity">
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.44"/>
<Button
android:id="@+id/btnThird"
android:layout_width="0dp"
app:layout_constraintHorizontal_weight="1"
android:layout_height="wrap_content"
android:text="@string/btnThird"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintRight_toLeftOf="@+id/btnTwoThirds"
app:layout_constraintBottom_toTopOf="@+id/guideline"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"/>
<Button
android:id="@+id/btnTwoThirds"
app:layout_constraintHorizontal_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/btnTwoThirds"
app:layout_constraintBottom_toBottomOf="@+id/btnThird"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="@+id/btnThird"/>
</android.support.constraint.ConstraintLayout>
If you go to references, click on the Entity Framework, view properties It will tell you the version number.
I used this statement.
$base = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]$my_web_base_path";
$url = $base . "/" . dirname(dirname(__FILE__));
I hope this will help you.
For MAC and LINUX use the following procedure:
Add the directory where composer.phar is located to you PATH:
export PATH=$PATH:/yourdirectory
and then rename composer.phar to composer:
mv composer.phar composer
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
we must also need to add following in build.gradle(app)
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
whenever we are using new layouts or new design features. hope this helps you.
You can do that on javascript side .
<input type="submit" value="Send It!" onClick="return ActionDeterminator();">
When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.
function ActionDeterminator() {
if(document.myform.reason[0].checked == true) {
document.myform.action = 'http://google.com';
}
if(document.myform.reason[1].checked == true) {
document.myform.action = 'http://microsoft.com';
document.myform.method = 'get';
}
if(document.myform.reason[2].checked == true) {
document.myform.action = 'http://yahoo.com';
}
return true;
}
After losing time and reading for a while, I just wanted something simple, this css worked for my requirements.
.gm-style-iw > div { overflow: hidden !important; }
Also is not an instant solution but starring/commenting on the issue might make them fix it, as they believe it is fixed: http://code.google.com/p/gmaps-api-issues/issues/detail?id=5713
The built-in timeit module works best from the IPython command line.
To time functions from within a module:
from timeit import default_timer as timer
import sys
def timefunc(func, *args, **kwargs):
"""Time a function.
args:
iterations=3
Usage example:
timeit(myfunc, 1, b=2)
"""
try:
iterations = kwargs.pop('iterations')
except KeyError:
iterations = 3
elapsed = sys.maxsize
for _ in range(iterations):
start = timer()
result = func(*args, **kwargs)
elapsed = min(timer() - start, elapsed)
print(('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, elapsed)))
return result
The problem is, os.path.join
doesn't take a list
as argument, it has to be separate arguments.
This is where *
, the 'splat' operator comes into play...
I can do
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
In case someone has this while trying to compile an Android project, there is an alternative Nullable implementation in android.support.annotation.Nullable
. So take care which package you've referenced in your import
s.
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
Use READ_UNCOMMITTED in situation where source is highly unlikely to change.
Don't use READ_UNCOMMITTED when you know souce may change during fetch operation.
When you're on a page that doesn't let you reach the SVG via its own URL (e.g. an inline SVG), you can print the page and select PDF as the target output. Once the PDF has been saved, you can open it in an image editor that supports vector (e.g. Adobe Illustrator), select only the vector art you want, and cut and paste it into a new file in the image editor.
This fixes some issues with Blorgbeard's answer (but is untested):
@echo off
cd /d "c:\Program files\IIS Express"
start "" iisexpress /path:"C:\FormsAdmin.Site" /port:8088 /clr:v2.0
timeout 10
start http://localhost:8088/default.aspx
pause
Maybe I didn't understand the question correctly, but can you not use keyup
if you want to capture both inputs?
$("input").bind("keyup",function(e){
var value = this.value + String.fromCharCode(e.keyCode);
});
You can use also system table_types view
IF EXISTS (SELECT *
FROM [sys].[table_types]
WHERE user_type_id = Type_id(N'[dbo].[UdTableType]'))
BEGIN
PRINT 'EXISTS'
END
Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.
After all, it's JSON, not JSAAN. :)
So PHP has to convert your array into an object in order to encode into JSON.
If your device knows the Wifi configs (already stored), we can bypass rocket science. Just loop through the configs an check if the SSID is matching. If so, connect and return.
Set permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Connect:
try {
String ssid = null;
if (wifi == Wifi.PCAN_WIRELESS_GATEWAY) {
ssid = AesPrefs.get(AesConst.PCAN_WIRELESS_SSID,
context.getString(R.string.pcan_wireless_ssid_default));
} else if (wifi == Wifi.KJ_WIFI) {
ssid = context.getString(R.string.remote_wifi_ssid_default);
}
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID);
wifiManager.reconnect();
return null; // return! (sometimes logcat showed me network-entries twice,
// which may will end in bugs)
}
}
} catch (NullPointerException | IllegalStateException e) {
Log.e(TAG, "connectToWifi: Missing network configuration.");
}
return null;
I believe that matplotlib has the ability to serialize graphics, text and other objects to a pdf document.
Here is a function I wrote. It wraps the base::source
function to store a list of sourced files in a global environment list named sourced
. It will only re-source a file if you provide a .force=TRUE
argument to the call to source. Its argument signature is otherwise identical to the real source()
so you don't need to rewrite your scripts to use this.
warning("overriding source with my own function FYI")
source <- function(path, .force=FALSE, ...) {
library(tools)
path <- tryCatch(normalizePath(path), error=function(e) path)
m<-md5sum(path)
go<-TRUE
if (!is.vector(.GlobalEnv$sourced)) {
.GlobalEnv$sourced <- list()
}
if(! is.null(.GlobalEnv$sourced[[path]])) {
if(m == .GlobalEnv$sourced[[path]]) {
message(sprintf("Not re-sourcing %s. Override with:\n source('%s', .force=TRUE)", path, path))
go<-FALSE
}
else {
message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
go<-TRUE
}
}
if(.force) {
go<-TRUE
message(" ...forcing.")
}
if(go) {
message(sprintf("sourcing %s", path))
.GlobalEnv$sourced[path] <- m
base::source(path, ...)
}
}
It's pretty chatty (lots of calls to message()
) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.
Based on the answer by Korakot Chaovavanich, I created the function below to download all files needed within a Colab instance.
from google.colab import files
def getLocalFiles():
_files = files.upload()
if len(_files) >0:
for k,v in _files.items():
open(k,'wb').write(v)
getLocalFiles()
You can then use the usual 'import' statement to import your local files in Colab. I hope this helps
you cannot see the groupBy data directly by print statement but you can see by iterating over the group using for loop try this code to see the group by data
group = df.groupby('A') #group variable contains groupby data
for A,A_df in group: # A is your column and A_df is group of one kind at a time
print(A)
print(A_df)
you will get an output after trying this as a groupby result
I hope it helps
In the System.Windows.Forms
class, you can find more on the MSDN page for this here. Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message");
or confirm("my question");
functions.
You can check for empty string (when stderr is empty)
- name: Check script
shell: . {{ venv_name }}/bin/activate && myscritp.py
args:
chdir: "{{ home }}"
sudo_user: "{{ user }}"
register: test_myscript
- debug: msg='myscritp is Ok'
when: test_myscript.stderr == ""
If you want to check for fail:
- debug: msg='myscritp has error: {{test_myscript.stderr}}'
when: test_myscript.stderr != ""
Also look at this stackoverflow question
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
Here is my solution :-
function frequent(number){_x000D_
var count = 0;_x000D_
var sortedNumber = number.sort();_x000D_
var start = number[0], item;_x000D_
for(var i = 0 ; i < sortedNumber.length; i++){_x000D_
if(start === sortedNumber[i] || sortedNumber[i] === sortedNumber[i+1]){_x000D_
item = sortedNumber[i]_x000D_
}_x000D_
}_x000D_
return item_x000D_
_x000D_
}_x000D_
_x000D_
console.log( frequent(['pear', 'apple', 'orange', 'apple']))
_x000D_
The header <math.h>
is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath>
is the C++ version of that header. It defines essentially the same stuff in namespace std
. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h>
doesn't exist.
Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std
. Or there's some macro magic for parsing the same header with or without namespace std
wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath>
be a one-liner including some other header with a .h
extension. Or some would map all includes matching <cblah>
to <blah.h>
(which, through macro magic, becomes the C++ header when __cplusplus
is defined, and otherwise becomes the C header) or <cblah.h>
or whatever.
That's the reason why on some platforms including things like <cmath.h>
, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.
I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath>
maps to <cmath.h>
with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.
Note, however, that this code still ought not to compile:
#include <cmath>
double f(double d)
{
return abs(d);
}
There shouldn't be an abs()
in the global namespace (it's std::abs()
). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.
Python
As @numeral correctly said, column._jc.toString()
works fine in case of unaliased columns.
In case of aliased columns (i.e. column.alias("whatever")
) the alias can be extracted, even without the usage of regular expressions: str(column).split(" AS ")[1].split("`")[1]
.
I don't know Scala syntax, but I'm sure It can be done the same.
They change it again. At this moment documentation does not fit actual situation.
Commonly all works as expected with one small difference. Login from Devices
config now moves to Products -> Facebook Login
.
So you need to:
App id
from headline,Client Token
from app Settings -> Advanced
. There is also Native or desktop app?
question/config. I turn it on.Add product
and then Get started
on Facebook login
. Move back to your app config, click to newly added Facebook login
and you'll see your Login from Devices
config.Just add two lines of code to make orientation of recyclerview as horizontal. So add these lines when Initializing Recyclerview.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
my_recycler.setLayoutManager(linearLayoutManager);
Have you entered the virtual environment for django? Run python -m venv myvenv
if you have not yet installed.
If listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.
You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
You could use a Data URI to supply the image data, for example:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
</svg>
The image will go through all normal svg transformations.
But this technique has disadvantages, for example the image will not be cached by the browser
As of my knowledge it is impossible to alter/modify a table type.You can create the type with a different name and then drop the old type and modify it to the new name
Credits to jkrajes
As per msdn, it is like 'The user-defined table type definition cannot be modified after it is created'.
As stated, use TextView.setText(Html.fromHtml(String))
And use these tags in your Html formatted string:
<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:
For example a recursive class could be a binary tree (or any tree):
class tree():
def __init__(self):
'''Initialise the tree'''
self.Data = None
self.Count = 0
self.LeftSubtree = None
self.RightSubtree = None
def Insert(self, data):
'''Add an item of data to the tree'''
if self.Data == None:
self.Data = data
self.Count += 1
elif data < self.Data:
if self.LeftSubtree == None:
# tree is a recurive class definition
self.LeftSubtree = tree()
# Insert is a recursive function
self.LeftSubtree.Insert(data)
elif data == self.Data:
self.Count += 1
elif data > self.Data:
if self.RightSubtree == None:
self.RightSubtree = tree()
self.RightSubtree.Insert(data)
if __name__ == '__main__':
T = tree()
# The root node
T.Insert('b')
# Will be put into the left subtree
T.Insert('a')
# Will be put into the right subtree
T.Insert('c')
As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.
Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :
import sys
sys.getrecursionlimit()
and to set it :
import sys #(if you haven't already)
sys.setrecursionlimit()
edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how
As a quick and dirty solution leveraging existing infrastructure, you can wrap your uglyPrintedMap
into a java.util.HashMap
, then use toString()
.
uglyPrintedMap.toString(); // ugly
System.out.println( uglyPrintedMap ); // prints in an ugly manner
new HashMap<Object, Object>(jobDataMap).toString(); // pretty
System.out.println( new HashMap<Object, Object>(uglyPrintedMap) ); // prints in a pretty manner
This is a common misunderstanding which leads to confusion if you use the same Scanner for nextLine() right after you used nextInt().
You can either fix the cursor jumping to the next Line by yourself or just use a different scanner for your Integers.
OPTION A: use 2 different scanners
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
Scanner intscan =new Scanner(System.in);
System.out.println("enter a no");
a=intscan.nextInt();
System.out.println("no is ="+a);
Scanner textscan=new Scanner(System.in);
System.out.println("enter a string");
s=textscan.nextLine();
System.out.println("string is="+s);
}
}
OPTION B: just jump to the next Line
class string
{
public static void main(String a[]){
int a;
String s;
Scanner scan =new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is ="+a);
scan.nextLine();
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is="+s);
}
}
This function handles also the invalid 29.2.2001 date.
function parseDate(str) {
var dateParts = str.split(".");
if (dateParts.length != 3)
return null;
var year = dateParts[2];
var month = dateParts[1];
var day = dateParts[0];
if (isNaN(day) || isNaN(month) || isNaN(year))
return null;
var result = new Date(year, (month - 1), day);
if (result == null)
return null;
if (result.getDate() != day)
return null;
if (result.getMonth() != (month - 1))
return null;
if (result.getFullYear() != year)
return null;
return result;
}
N.B. These notes are for SQL Server Express 2008 R2 (so Microsoft still haven't made this any easier). I also realise that I complicated things by installing 32-bit SQL Server Express 2005 and 64-bit SQL Server Express 2008.
I followed the steps by Josh Hinman above. Uninstalling the SQL Server Express 2005 "Workstation Components" was not enough. I required an uninstall of the 2005 Management Studio as well.
I also tried the Upgrade route that Josh Hinman suggested by clicking on the 'Upgrade from SQL Server 2000, SQL Server 2005 or SQL Server 2008'. This route never gave me the option of installing the components side-by-side it just went straight through the process of upgrading from 2005 to 2008. It completed successfully - but hadn't actually done anything. Thankfully though it hadn't harmed any existing database instances. So be warned trying that route.
Seems like you want to move around. Try this:
ActiveSheet.UsedRange.select
results in....
If you want to move that selection 3 rows up then try this
ActiveSheet.UsedRange.offset(-3).select
does this...
list all your docker images:
docker images
list all existed docker containers:
docker ps -a
delete all the targeted containers, which is using the image that you want to delete:
docker rm <container-id>
delete the targeted image:
docker rmi <image-name:image-tag or image-id>
What you're missing is running composer install
, which will import your packages and create the vendor folder, along with the autoload script.
Make sure your relative path is correct. For example the example scripts in PHPMailer are in examples/
, below the project root, so the correct relative path to load the composer autoloader from there would be ../vendor/autoload.php
.
The autoload.php you found in C:\Windows\SysWOW64\vendor\autoload.php
is probably a global composer installation – where you'll usually put things like phpcs, phpunit, phpmd etc.
composer update
is not the same thing, and probably not what you want to use. If your code is tested with your current package versions then running update
may cause breakages which may require further work and testing, so don't run update
unless you have a specific reason to and understand exactly what it means. To clarify further – you should probably only ever run composer update
locally, never on your server as it is reasonably likely to break apps in production.
I often see complaints that people can't use composer because they can't run it on their server (e.g. because it's shared and they have no shell access). In that case, you can still use composer: run it locally (an environment that has no such restrictions), and upload the local vendor folder it generates along with all your other PHP scripts.
Running composer update
also performs a composer install
, and if you do not currently have a vendor
folder (normal if you have a fresh checkout of a project), then it will create one, and also overwrite any composer.lock
file you already have, updating package versions tagged in it, and this is what is potentially dangerous.
Similarly, if you do not currently have a composer.lock
file (e.g. if it was not committed to the project), then composer install
also effectively performs a composer update
. It's thus vital to understand the difference between the two as they are definitely not interchangeable.
It is also possible to update a single package by naming it, for example:
composer update ramsey/uuid
This will re-resolve the version specified in your composer.json
and install it in your vendor folder, and update your composer.lock
file to match. This is far less likely to cause problems than a general composer update
if you just need a specific update to one package.
It is normal for libraries to not include a composer.lock
file of their own; it's up to apps to fix versions, not the libraries they use. As a result, library developers are expected to maintain compatibility with a wider range of host environments than app developers need to. For example, a library might be compatible with Laravel 5, 6, 7, and 8, but an app using it might require Laravel 8 for other reasons.
Composer 2.0 (out soon) should remove any remaining inconsistencies between install and update results.
cleanBuildCache
no longer works.
Android Gradle plugin now utilizes Gradle cache feature
https://guides.gradle.org/using-build-cache/
TO CLEAR CACHE
Clean the cache directory to avoid any hits from previous builds
rm -rf $GRADLE_HOME/caches/build-cache-*
https://guides.gradle.org/using-build-cache/#caching_android_projects
Other digressions: see here (including edits).
Newest solution using Gradle task:
cleanBuildCache
Available via Android plugin for Gradle, revision 2.3.0 (February 2017)
Dependencies:
More info at:
https://developer.android.com/studio/build/build-cache.html#clear_the_build_cache
Build cache
Stores certain outputs that the Android plugin generates when building your project (such as unpackaged AARs and pre-dexed remote dependencies). Your clean builds are much faster while using the cache because the build system can simply reuse those cached files during subsequent builds, instead of recreating them. Projects using Android plugin 2.3.0 and higher use the build cache by default. To learn more, read Improve Build Speed with Build Cache.
NOTE: The cleanBuildCache task is not available if you disable the build cache.
Windows:
gradlew cleanBuildCache
Linux / Mac:
gradle cleanBuildCache
Android Studio / IntelliJ:
gradle tab (default on right) select and run the task or add it via the configuration window
NOTE: gradle
/ gradlew
are system specific files containing scripts. Please see the related system info how to execute the scripts:
On my Mac this is what worked for me
You are good to go and can now run your project
Recently added a composite key with the uniqueness of 2 columns using the approach that 'chuck' recommended, thank @chuck. Only this approached looked cleaner to me:
public int groupId {get; set;}
[Index("IX_ClientGrouping", 1, IsUnique = true)]
public int ClientId { get; set; }
[Index("IX_ClientGrouping", 2, IsUnique = true)]
public int GroupName { get; set; }
Here is an elegant solution if your server supports the TRANSLATE function (on sql server it's available on sql server 2017+ and also sql azure).
First, it replaces any non numeric characters with a @ character. Then, it removes all @ characters. You may need to add additional characters that you know may be present in the second parameter of the TRANSLATE call.
select REPLACE(TRANSLATE([Col], 'abcdefghijklmnopqrstuvwxyz+()- ,#+', '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'), '@', '')
To execute more Maven builds from one script you shall use the Windows call function in the following way:
call mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar -Dpackaging=jar -DgeneratePom=true
The file module doesn't copy files on the remote system. The src parameter is only used by the file module when creating a symlink to a file.
If you want to move/rename a file entirely on a remote system then your best bet is to use the command module to just invoke the appropriate command:
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
If you want to get fancy then you could first use the stat module to check that foo actually exists:
- name: stat foo
stat: path=/path/to/foo
register: foo_stat
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
when: foo_stat.stat.exists
You can do this:
If your tomcat installation is default and you have not done any changes, then the default war will be ROOT.war
. Thus whenever you will call http://yourserver.example.com/
, it will call the index.html
or index.jsp
of your default WAR file. Make the following changes in your webapp/ROOT
folder for redirecting requests to http://yourserver.example.com/somewhere/else
:
Open webapp/ROOT/WEB-INF/web.xml
,
remove any servlet mapping with path /index.html
or /index.jsp
,
and save.
Remove webapp/ROOT/index.html
, if it exists.
Create the file webapp/ROOT/index.jsp
with this line of content:
<% response.sendRedirect("/some/where"); %>
or if you want to direct to a different server,
<% response.sendRedirect("http://otherserver.example.com/some/where"); %>
That's it.
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
Is there a way in which I can update the plot just by adding more point[s] to it...
There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.
Each method basically sets the data
property of the object being drawn, so doesn't require clearing the screen or figure. The data
property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).
Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:
import matplotlib.pyplot as plt
import numpy
hl, = plt.plot([], [])
def update_line(hl, new_data):
hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
plt.draw()
Then when you receive data from the serial port just call update_line
.
I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).
If you dont have identity column in table B_table:
INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table
If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.
In case if you dont have existing B_table in B_db
SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table
will create table B_table in database B_db with all existing values
It's called on Object Literal
I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.
var formObject = {"formObject": [
{"firstName": firstName, "lastName": lastName},
{"phoneNumber": phone},
{"address": address},
]}
Although this seems to make more sense (Why do you have an array in the above literal?):
var formObject = {
firstName: firstName
...
}
Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.
Hey there, this works for me (I couldn't get this working with the Google API links you were using):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Beef Burrito</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
</head>
<body>
<div class="draggable" style="border: 1px solid black; width: 50px; height: 50px; position: absolute; top: 0px; left: 0px;">asdasd</div>
<script type="text/javascript">
$(".draggable").draggable();
</script>
</body>
</html>
Routes
export const MyRoutes: Routes = [
{ path: '/items/:id', component: MyComponent }
]
Component
import { ActivatedRoute } from '@angular/router';
public id: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
}
You need to disable the button in the onsubmit
event of the <form>
:
<form action='/' method='POST' onsubmit='disableButton()'>
<input name='txt' type='text' required />
<button id='btn' type='submit'>Post</button>
</form>
<script>
function disableButton() {
var btn = document.getElementById('btn');
btn.disabled = true;
btn.innerText = 'Posting...'
}
</script>
Note: this way if you have a form element which has the required
attribute will work.
The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.
You can use ax.figure.savefig()
, as suggested in a comment on the question:
import pandas as pd
df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
Try this,
var _My_ResetSet_Array = _DB
.tbl_MyTable
.Where(x => x.Active == true
&& x.DateTimeValueColumn <= DateTime.Now)
.Select(x => x.DateTimeValueColumn)
.AsEnumerable()
.select(p=>p.DateTimeValueColumn.value.toString("YYYY-MMM-dd");
Try to use this one
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^]
is for negation, \w
for [a-zA-Z0-9_]
word characters and \s
for space,
/[]/g
for global
The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:
function getMachine(color, qty) {
var returnValue = null;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
returnValue = thisArray[3];
return false; // this breaks out of the each
}
});
return returnValue;
}
var retval = getMachine(color, qty);
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
What about getting the string representation of the lists and comparing them ?
>>> l1 = ['one', 'two', 'three']
>>> l2 = ['one', 'two', 'three']
>>> l3 = ['one', 'three', 'two']
>>> print str(l1) == str(l2)
True
>>> print str(l1) == str(l3)
False
You can disable all security by editing /etc/my.cnf:
[mysqld]
skip-grant-tables
Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.
CODE:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
you can only make circle from square using border-radius.
border-radius doesn't increase or reduce heights nor widths.
Your request is to use only image tag , it is basicly not possible if tag is not a square.
If you want to use a blank image and set another in bg, it is going to be painfull , one background for each image to set.
Cropping can only be done if a wrapper is there to do so. inthat case , you have many ways to do it
In Bootstrap 4:
to center the child horizontally, use bootstrap-4 class:
justify-content-center
to center the child vertically, use bootstrap-4 class:
align-items-center
but remember don't forget to use d-flex class with these it's a bootstrap-4 utility class, like so
<div class="d-flex justify-content-center align-items-center" style="height:100px;">
<span class="bg-primary">MIDDLE</span>
</div>
Note: make sure to add bootstrap-4 utilities if this code does not work
I know it's not the direct answer to this question but it may help someone
I see a few things wrong.
char
, so that will cause issues.if char == word[count]
instead of word[some index]
You don't even need the while
. If you rename the char param to search
,
for char in word:
if char == search:
count += 1
return count
Yes, you can combine columns easily enough such as concatenating character data:
select col1 | col 2 as bothcols from tbl ...
or adding (for example) numeric data:
select col1 + col2 as bothcols from tbl ...
In both those cases, you end up with a single column bothcols
, which contains the combined data. You may have to coerce the data type if the columns are not compatible.
If it's going into an HTML attribute, you'll need to both HTML-encode (as a minimum: >
to >
<
to <
and "
to "
) it, and escape single-quotes (with a backslash) so they don't interfere with your javascript quoting.
Best way to do it is with your templating system (extending it, if necessary), but you could simply make a couple of escaping/encoding functions and wrap them both around any data that's going in there.
And yes, it's perfectly valid (correct, even) to HTML-escape the entire contents of your HTML attributes, even if they contain javascript.
Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...
list = [1,2,3,4,5]
deleteList = []
processNo = 0
for item in list:
if condition:
print item
deleteList.insert(0, processNo)
processNo += 1
if len(deleteList) > 0:
for item in deleteList:
del list[item]
It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
Although this an old post, I am sharing another working example.
"COLUMN COUNT AS WELL AS EACH COLUMN DATATYPE MUST MATCH WHEN 'UNION' OR 'UNION ALL' IS USED"
Let us take an example:
In SQL if we write - SELECT 'column1', 'column2' (NOTE: remember to specify names in quotes) In a result set, it will display empty columns with two headers - column1 and column2
I had seven columns with few different datatypes in SQL. I.e. uniqueidentifier, datetime, nvarchar
My task was to retrieve comma separated result set with column header. So that when I export the data to CSV I have comma separated rows with first row as header and has respective column names.
SELECT CONVERT(NVARCHAR(36), 'Event ID') + ', ' +
'Last Name' + ', ' +
'First Name' + ', ' +
'Middle Name' + ', ' +
CONVERT(NVARCHAR(36), 'Document Type') + ', ' +
'Event Type' + ', ' +
CONVERT(VARCHAR(23), 'Last Updated', 126)
UNION ALL
SELECT CONVERT(NVARCHAR(36), inspectionid) + ', ' +
individuallastname + ', ' +
individualfirstname + ', ' +
individualmiddlename + ', ' +
CONVERT(NVARCHAR(36), documenttype) + ', ' +
'I' + ', ' +
CONVERT(VARCHAR(23), modifiedon, 126)
FROM Inspection
Above, columns 'inspectionid' & 'documenttype' has uniqueidentifer
datatype and so applied CONVERT(NVARCHAR(36))
. column 'modifiedon' is datetime and so applied CONVERT(NVARCHAR(23), 'modifiedon', 126)
.
Parallel to above 2nd SELECT
query matched 1st SELECT
query as per datatype of each column.
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
Or you can simply use OleDbDataAdapter to get data from Excel
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
You can use a try-except
try:
print(str.to.id)
except AttributeError: # Not a Retweet
print('null')
I use a custom style
<style name="MyButtonStyle" parent="@style/Widget.AppCompat.Button.Borderless"></style>
Don't forget to add
<item name="android:textAllCaps">false</item>
otherwise the button text will be in UpperCase.
In addition, if you wish to parse your object in case of http error (400-5** codes), You can use the following code: (just replace 'getInputStream' with 'getErrorStream':
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
In iOS8 sizeWithFont has been deprecated, please refer to
CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];
You can add all the attributes you want in sizeWithAttributes. Other attributes you can set:
- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName
and so on. But probably you won't need the others
I know this is a bit old, but i thought i would contribute. Basing myself on the answer by @Sophy, this is what I did to add a .xxs breakpoint. I have not taken care of visible-inline, table.visible, etc classes.
/*========== Mobile First Method ==========*/
.col-xxs-12, .col-xxs-11, .col-xxs-10, .col-xxs-9, .col-xxs-8, .col-xxs-7, .col-xxs-6, .col-xxs-5, .col-xxs-4, .col-xxs-3, .col-xxs-2, .col-xxs-1 {
position: relative;
min-height: 1px;
padding-left: 15px;
padding-right: 15px;
float: left;
}
.visible-xxs {
display:none !important;
}
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) and (max-width:479px) {
.visible-xxs {
display: block !important;
}
.visible-xs {
display:none !important;
}
.hidden-xs {
display:block !important;
}
.hidden-xxs {
display:none !important;
}
.col-xxs-12 {
width: 100%;
}
.col-xxs-11 {
width: 91.66666667%;
}
.col-xxs-10 {
width: 83.33333333%;
}
.col-xxs-9 {
width: 75%;
}
.col-xxs-8 {
width: 66.66666667%;
}
.col-xxs-7 {
width: 58.33333333%;
}
.col-xxs-6 {
width: 50%;
}
.col-xxs-5 {
width: 41.66666667%;
}
.col-xxs-4 {
width: 33.33333333%;
}
.col-xxs-3 {
width: 25%;
}
.col-xxs-2 {
width: 16.66666667%;
}
.col-xxs-1 {
width: 8.33333333%;
}
.col-xxs-pull-12 {
right: 100%;
}
.col-xxs-pull-11 {
right: 91.66666667%;
}
.col-xxs-pull-10 {
right: 83.33333333%;
}
.col-xxs-pull-9 {
right: 75%;
}
.col-xxs-pull-8 {
right: 66.66666667%;
}
.col-xxs-pull-7 {
right: 58.33333333%;
}
.col-xxs-pull-6 {
right: 50%;
}
.col-xxs-pull-5 {
right: 41.66666667%;
}
.col-xxs-pull-4 {
right: 33.33333333%;
}
.col-xxs-pull-3 {
right: 25%;
}
.col-xxs-pull-2 {
right: 16.66666667%;
}
.col-xxs-pull-1 {
right: 8.33333333%;
}
.col-xxs-pull-0 {
right: auto;
}
.col-xxs-push-12 {
left: 100%;
}
.col-xxs-push-11 {
left: 91.66666667%;
}
.col-xxs-push-10 {
left: 83.33333333%;
}
.col-xxs-push-9 {
left: 75%;
}
.col-xxs-push-8 {
left: 66.66666667%;
}
.col-xxs-push-7 {
left: 58.33333333%;
}
.col-xxs-push-6 {
left: 50%;
}
.col-xxs-push-5 {
left: 41.66666667%;
}
.col-xxs-push-4 {
left: 33.33333333%;
}
.col-xxs-push-3 {
left: 25%;
}
.col-xxs-push-2 {
left: 16.66666667%;
}
.col-xxs-push-1 {
left: 8.33333333%;
}
.col-xxs-push-0 {
left: auto;
}
.col-xxs-offset-12 {
margin-left: 100%;
}
.col-xxs-offset-11 {
margin-left: 91.66666667%;
}
.col-xxs-offset-10 {
margin-left: 83.33333333%;
}
.col-xxs-offset-9 {
margin-left: 75%;
}
.col-xxs-offset-8 {
margin-left: 66.66666667%;
}
.col-xxs-offset-7 {
margin-left: 58.33333333%;
}
.col-xxs-offset-6 {
margin-left: 50%;
}
.col-xxs-offset-5 {
margin-left: 41.66666667%;
}
.col-xxs-offset-4 {
margin-left: 33.33333333%;
}
.col-xxs-offset-3 {
margin-left: 25%;
}
.col-xxs-offset-2 {
margin-left: 16.66666667%;
}
.col-xxs-offset-1 {
margin-left: 8.33333333%;
}
.col-xxs-offset-0 {
margin-left: 0%;
}
}
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {
.visible-xs {
display:block !important;
}
}
/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
.visible-xs {
display:none !important;
}
}
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
}
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
}
A nifty non-caching async one liner for node 15 modules:
import { readFile } from 'fs/promises';
const data = await readFile('{{ path }}').then(json => JSON.parse(json)).catch(() => null);
Full disclosure, I am one of the maintainers of pdfminer.six.
Nowadays, there are multiple api's to extract text from a PDF, depending on your needs. Behind the scenes, all of these api's use the same logic for parsing and analyzing the layout.
(All the examples assume your PDF file is called example.pdf)
Commandline
If you want to extract text just once you can use the commandline tool pdf2txt.py:
$ pdf2txt.py example.pdf
High-level api
If you want to extract text with Python, you can use the high-level api. This approach is the go-to solution if you want to extract text programmatically from many PDF's.
from pdfminer.high_level import extract_text
text = extract_text('example.pdf')
Composable api
There is also a composable api that gives a lot of flexibility in handling the resulting objects. For example, you can implement your own layout algorithm using that. This method is suggested in the other answers, but I would only recommend this when you need to customize the way pdfminer.six behaves.
from io import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
output_string = StringIO()
with open('example.pdf', 'rb') as in_file:
parser = PDFParser(in_file)
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.create_pages(doc):
interpreter.process_page(page)
print(output_string.getvalue())
Open the svg using Inkscape.
Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/
done
all rect/circle have been converted to path
A quick and copy/paste you can use for Chrome and Firefox would be: (change the stuff after the # to change the color)
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
-border-radius: 10px;
-moz-box-shadow: 0 0 15px 5px #666;
-webkit-box-shadow: 0 0 15px 05px #666;
Matt Roberts' answer is correct for webkit browsers (safari, chrome, etc), but I thought someone out there might want a quick answer rather than be told to learn to program to make some shadows.
I have used this function for access properties of the deeply nested object and it working for me...
this is the function
/**
* get property of object
* @param obj object
* @param path e.g user.name
*/
getProperty(obj, path, defaultValue = '-') {
const value = path.split('.').reduce((o, p) => o && o[p], obj);
return value ? value : defaultValue;
}
this is how I access the deeply nested object property
{{ getProperty(object, 'passengerDetails.data.driverInfo.currentVehicle.vehicleType') }}
BufferedReader bf= new BufferedReader(new FileReader("G://Sample.txt"));
String line=bf.readLine();
while(line!=null)
{
String[] words=line.split(" ");
System.out.println("this line contains " +words.length+ " words");
line=bf.readLine();
}
You can use html
instead of text
and replace each occurrence of \n
with <br>
. You will have to correctly escape your text though.
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
This answer will be useful for those who use a non-standard IDE (i.e. Qt Creator).
There are at least two non-intrusive ways to pass additional include paths to Visual Studio's cl.exe
via environment variables:
INCLUDE
environment variable to ;
-separated list of all include paths. It overrides all includes, inclusive standard library ones. Not recommended.CL
environment variable to the following value: /I C:\Lib\VulkanMemoryAllocator\src /I C:\Lib\gli /I C:\Lib\gli\external
, where each argument of /I
key is additional include path.I successfully use the last one.
I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
Create a new folder, let's say local-maven-repo
at the root of your Maven project.
Just add a local repo iside your <project>
of your pom.xml
:
<repositories>
<repository>
<id>local-maven-repo</id>
<url>file:///${project.basedir}/local-maven-repo</url>
</repository>
</repositories>
Then for each external jar you want to install, go at the root of your project and execute:
mvn deploy:deploy-file -DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] -Durl=file:./local-maven-repo/ -DrepositoryId=local-maven-repo -DupdateReleaseInfo=true -Dfile=[FILE_PATH]
(Copied from my reply on a similar question)
The code is very long so I can't paste all the code.
There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.
You need to create a SSCCE to post on the forum.
So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.
Learn how the basice work first before writing a 200 line program.
Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.
In objective c you can use CGRectContainsPoint(yourview.frame, touchpoint)
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch* touch = [touches anyObject];
CGPoint touchpoint = [touch locationInView:self.view];
if( CGRectContainsPoint(yourview.frame, touchpoint) ) {
}else{
}}
In swift 3 yourview.frame.contains(touchpoint)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first!
let touchpoint:CGPoint = touch.location(in: self.view)
if wheel.frame.contains(touchpoint) {
}else{
}
}
The getRow()
method will always yield 0 after a query:
Retrieves the current row number.
Second, you output totalrec
but never assign anything to it.
Give each input
a name
attribute. Only the clicked input
's name
attribute will be sent to the server.
<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">
And then
<?php
if (isset($_POST['publish'])) {
# Publish-button was clicked
}
elseif (isset($_POST['save'])) {
# Save-button was clicked
}
?>
Edit: Changed value
attributes to alt
. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]
?
Edit: Since this keeps getting upvotes I went ahead and changed the weird alt
/value
code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image]
.
I've found that the parseArgs function can be very helpful.
Bootstrap 4 has a new notation for margin and padding classes. Refer to Bootstrap 4.0 Documentation - Spacing.
From the documentation:
Notation
Spacing utilities that apply to all breakpoints, from
xs
toxl
, have no breakpoint abbreviation in them. This is because those classes are applied frommin-width: 0
and up, and thus are not bound by a media query. The remaining breakpoints, however, do include a breakpoint abbreviation.The classes are named using the format
{property}{sides}-{size}
forxs
and{property}{sides}-{breakpoint}-{size}
forsm
,md
,lg
, andxl
.Examples
.mt-0 { margin-top: 0 !important; }
.p-3 { padding: $spacer !important; }
Or you could just perform a trim()
on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
make use of (Type Properties)
Name Gets the name of the current member. (Inherited from MemberInfo.)
Example : typeof(T).Name;
There are several ways to do it, but here is one solution (for 4 columns).
string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);
And a more verbose way is here:
ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");
ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");
ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");
ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});
I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.
I just made two changes and I don't which help.
Go to IIS 6 Manager
Select properties of SMTP server
On tab Access, select Relays
Add your public IP address
Close the dialog and on the same tab click to Authentication button.
Add Integrated Windows Authentication
Maybe some step is not needed, but it works.
This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.
Here are the steps I found to work.
Use pdfimages
from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.
Use Tesseract to detect rotation and ImageMagick mogrify
to fix it.
Use OpenCV to find and extract tables.
Use OpenCV to find and extract each cell from the table.
Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.
Use Tesseract to OCR each cell.
Combine the extracted text of each cell into the format you need.
I wrote a python package with modules that can help with those steps.
Repo: https://github.com/eihli/image-table-ocr
Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html
Some of the steps don't require code, they take advantage of external tools like pdfimages
and tesseract
. I'll provide some brief examples for a couple of the steps that do require code.
This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/
import cv2
def find_tables(image):
BLUR_KERNEL_SIZE = (17, 17)
STD_DEV_X_DIRECTION = 0
STD_DEV_Y_DIRECTION = 0
blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
MAX_COLOR_VAL = 255
BLOCK_SIZE = 15
SUBTRACT_FROM_MEAN = -2
img_bin = cv2.adaptiveThreshold(
~blurred,
MAX_COLOR_VAL,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
BLOCK_SIZE,
SUBTRACT_FROM_MEAN,
)
vertical = horizontal = img_bin.copy()
SCALE = 5
image_width, image_height = horizontal.shape
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)
horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))
mask = horizontally_dilated + vertically_dilated
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
)
MIN_TABLE_AREA = 1e5
contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
epsilons = [0.1 * p for p in perimeter_lengths]
approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
bounding_rects = [cv2.boundingRect(a) for a in approx_polys]
# The link where a lot of this code was borrowed from recommends an
# additional step to check the number of "joints" inside this bounding rectangle.
# A table should have a lot of intersections. We might have a rectangular image
# here though which would only have 4 intersections, 1 at each corner.
# Leaving that step as a future TODO if it is ever necessary.
images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
return images
This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.
We want to identify the cells from left-to-right, top-to-bottom.
We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.
def cell_in_same_row(c1, c2):
c1_center = c1[1] + c1[3] - c1[3] / 2
c2_bottom = c2[1] + c2[3]
c2_top = c2[1]
return c2_top < c1_center < c2_bottom
orig_cells = [c for c in cells]
rows = []
while cells:
first = cells[0]
rest = cells[1:]
cells_in_same_row = sorted(
[
c for c in rest
if cell_in_same_row(c, first)
],
key=lambda c: c[0]
)
row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
rows.append(row_cells)
cells = [
c for c in rest
if not cell_in_same_row(c, first)
]
# Sort rows by average height of their center.
def avg_height_of_center(row):
centers = [y + h - h / 2 for x, y, w, h in row]
return sum(centers) / len(centers)
rows.sort(key=avg_height_of_center)
Just disable IPv6
on the network configuration
Adding the following $cfg helps to narrow down the problem
$cfg['Error_Handler']['display'] = true;
$cfg['Error_Handler']['gather'] = true;
Don't forget to remove those $cfg after done debugging!
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
Building up on @peeol's excellent answer, you can also remove the frame by doing
for spine in plt.gca().spines.values():
spine.set_visible(False)
To give an example (the entire code sample can be found at the end of this post), let's say you have a bar plot like this,
you can remove the frame with the commands above and then either keep the x-
and ytick
labels (plot not shown) or remove them as well doing
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
In this case, one can then label the bars directly; the final plot could look like this (code can be found below):
Here is the entire code that is necessary to generate the plots:
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
xvals = list('ABCDE')
yvals = np.array(range(1, 6))
position = np.arange(len(xvals))
mybars = plt.bar(position, yvals, align='center', linewidth=0)
plt.xticks(position, xvals)
plt.title('My great data')
# plt.show()
# get rid of the frame
for spine in plt.gca().spines.values():
spine.set_visible(False)
# plt.show()
# remove all the ticks and directly label each bar with respective value
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
# plt.show()
# direct label each bar with Y axis values
for bari in mybars:
height = bari.get_height()
plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()-0.2, str(int(height)),
ha='center', color='white', fontsize=15)
plt.show()
I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.
I`ve been looking for something like this for ages... So i hope this helps someone!
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
namespace User
{
public static class UserValidation
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonProviders : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
enum LogonTypes : uint
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkCleartext = 8,
NewCredentials = 9
}
public const int ERROR_PASSWORD_MUST_CHANGE = 1907;
public const int ERROR_LOGON_FAILURE = 1326;
public const int ERROR_ACCOUNT_RESTRICTION = 1327;
public const int ERROR_ACCOUNT_DISABLED = 1331;
public const int ERROR_INVALID_LOGON_HOURS = 1328;
public const int ERROR_NO_LOGON_SERVERS = 1311;
public const int ERROR_INVALID_WORKSTATION = 1329;
public const int ERROR_ACCOUNT_LOCKED_OUT = 1909; //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
public const int ERROR_ACCOUNT_EXPIRED = 1793;
public const int ERROR_PASSWORD_EXPIRED = 1330;
public static int CheckUserLogon(string username, string password, string domain_fqdn)
{
int errorCode = 0;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
{
if (!pc.ValidateCredentials(username, password))
{
IntPtr token = new IntPtr();
try
{
if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
{
errorCode = Marshal.GetLastWin32Error();
}
}
catch (Exception)
{
throw;
}
finally
{
CloseHandle(token);
}
}
}
return errorCode;
}
}
That's like asking how long it would take to learn French:
Then again, plenty of people (most normal people, non-programmers) never learn those subjects, so if you're like "most" people then the answer would be "it would take forever" or "it will never happen".
The trim() method removes whitespace from both sides of a string.
You can use a Javascript replace method to remove white space like
"hello world".replace(/\s/g, "");
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
Couple of points:
git stash
+ git stash drop
could be replaced with git reset --hard
... or, even shorter, add -f
to checkout
command:
git checkout -f -b $branch
That will discard any local changes, just as if git reset --hard
was used prior to checkout.
As for the main question:
instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch
, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.
The easiest way with BS3 is to reset the max-width and padding set by BS3 CSS simply like this. You get again a container-fluid :
.container{
max-width:100%;
padding:0;
}
The answer depends on your view point:
If you judge by the C++ standard, you cannot get a null reference because you get undefined behavior first. After that first incidence of undefined behavior, the standard allows anything to happen. So, if you write *(int*)0
, you already have undefined behavior as you are, from a language standard point of view, dereferencing a null pointer. The rest of the program is irrelevant, once this expression is executed, you are out of the game.
However, in practice, null references can easily be created from null pointers, and you won't notice until you actually try to access the value behind the null reference. Your example may be a bit too simple, as any good optimizing compiler will see the undefined behavior, and simply optimize away anything that depends on it (the null reference won't even be created, it will be optimized away).
Yet, that optimizing away depends on the compiler to prove the undefined behavior, which may not be possible to do. Consider this simple function inside a file converter.cpp
:
int& toReference(int* pointer) {
return *pointer;
}
When the compiler sees this function, it does not know whether the pointer is a null pointer or not. So it just generates code that turns any pointer into the corresponding reference. (Btw: This is a noop since pointers and references are the exact same beast in assembler.) Now, if you have another file user.cpp
with the code
#include "converter.h"
void foo() {
int& nullRef = toReference(nullptr);
cout << nullRef; //crash happens here
}
the compiler does not know that toReference()
will dereference the passed pointer, and assume that it returns a valid reference, which will happen to be a null reference in practice. The call succeeds, but when you try to use the reference, the program crashes. Hopefully. The standard allows for anything to happen, including the appearance of pink elephants.
You may ask why this is relevant, after all, the undefined behavior was already triggered inside toReference()
. The answer is debugging: Null references may propagate and proliferate just as null pointers do. If you are not aware that null references can exist, and learn to avoid creating them, you may spend quite some time trying to figure out why your member function seems to crash when it's just trying to read a plain old int
member (answer: the instance in the call of the member was a null reference, so this
is a null pointer, and your member is computed to be located as address 8).
So how about checking for null references? You gave the line
if( & nullReference == 0 ) // null reference
in your question. Well, that won't work: According to the standard, you have undefined behavior if you dereference a null pointer, and you cannot create a null reference without dereferencing a null pointer, so null references exist only inside the realm of undefined behavior. Since your compiler may assume that you are not triggering undefined behavior, it can assume that there is no such thing as a null reference (even though it will readily emit code that generates null references!). As such, it sees the if()
condition, concludes that it cannot be true, and just throw away the entire if()
statement. With the introduction of link time optimizations, it has become plain impossible to check for null references in a robust way.
Null references are somewhat of a ghastly existence:
Their existence seems impossible (= by the standard),
but they exist (= by the generated machine code),
but you cannot see them if they exist (= your attempts will be optimized away),
but they may kill you unaware anyway (= your program crashes at weird points, or worse).
Your only hope is that they don't exist (= write your program to not create them).
I do hope that will not come to haunt you!
To get GCC to print out the complete set of directories where it will look for system headers, invoke it like this:
$ LC_ALL=C gcc -v -E -xc - < /dev/null 2>&1 |
LC_ALL=C sed -ne '/starts here/,/End of/p'
which will produce output of the form
#include "..." search starts here:
#include <...> search starts here:
/usr/lib/gcc/x86_64-linux-gnu/5/include
/usr/local/include
/usr/lib/gcc/x86_64-linux-gnu/5/include-fixed
/usr/include/x86_64-linux-gnu
/usr/include
End of search list.
If you have -I
-family options on the command line they will affect what is printed out.
(The sed
command is to get rid of all the other junk this invocation prints, and the LC_ALL=C
is to ensure that the sed
command works -- the "starts here" and "End of search list" phrases are translated IIRC.)
Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel
And for PDF
generation use http://princexml.com/
first find your binaries file where it is saved. get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
all done!
autovaccum launcher started! cheers!
Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:
General Syntax:
void* pointer_variable;
void *pVoid; // pVoid is a void pointer
A void pointer can point to objects of any data type:
int nValue;
float fValue;
struct Something
{
int nValue;
float fValue;
};
Something sValue;
void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid
However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
int nValue = 5;
void *pVoid = &nValue;
// can not dereference pVoid because it is a void pointer
int *pInt = static_cast<int*>(pVoid); // cast from void* to int*
cout << *pInt << endl; // can dereference pInt
Source: link
This can also be handled using the elvis operator ?:
which will add a default value when the field is null:
<span th:text="${object.property} ?: 'default value'"></span>
php artisan key:generate
php artisan config:cache
worked for me, but it had to be done in a command prompt on Windows.
Doing it inside the terminal in PHPStorm didn't worked.
The best way is to use q
parameter so that it displays the map with the point marked. eg.:
https://maps.google.com/?q=<lat>,<lng>
def copy_myfile_dirOne_to_dirSec(src, dest, ext):
if not os.path.exists(dest): # if dest dir is not there then we create here
os.makedirs(dest);
for item in os.listdir(src):
if item.endswith(ext):
s = os.path.join(src, item);
fd = open(s, 'r');
data = fd.read();
fd.close();
fname = str(item); #just taking file name to make this name file is destination dir
d = os.path.join(dest, fname);
fd = open(d, 'w');
fd.write(data);
fd.close();
print("Files are copyed successfully")
It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>
The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:
if (element.is(":checkbox")) {
error.insertAfter(element.parent().parent());
}
else {
error.insertAfter(element);
}
It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.
Just wrap it around then.
<?php
if ( ($cart->count_product) > 0)
{
echo "<div class='my_class'>";
print $cart->count_product;
echo "</div>";
}
?>
I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.
TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
Well, my solution is sort of hack, but it works and I am using it.
1vw = 1% of viewport width
1vh = 1% of viewport height
1vmin = 1vw or 1vh, whichever is smaller
1vmax = 1vw or 1vh, whichever is larger
h1 {
font-size: 5.9vw;
}
h2 {
font-size: 3.0vh;
}
p {
font-size: 2vmin;
}
Or, if spacing is not the problem, it might want the parent directory name rather than the file name.
Not $ dev_appserver helloapp.py
But $ dev_appserver hello/
For example:
Johns-Mac:hello john$ dev_appserver.py helloworld.py
Traceback (most recent call last):
File "/usr/local/bin/dev_appserver.py", line 82, in <module>
_run_file(__file__, globals())
...
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/yaml_listener.py", line 212, in _GenerateEventParameters
raise yaml_errors.EventListenerYAMLError(e)
google.appengine.api.yaml_errors.EventListenerYAMLError: mapping values are not allowed here
in "helloworld.py", line 3, column 39
Versus
Johns-Mac:hello john$ cd ..
Johns-Mac:fbm john$ dev_appserver.py hello/
INFO 2014-09-15 11:44:27,828 api_server.py:171] Starting API server at: http://localhost:61049
INFO 2014-09-15 11:44:27,831 dispatcher.py:183] Starting module "default" running at: http://localhost:8080
dataString suggests the data is formatted in a string (and maybe delimted by a character).
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
}
if dataString is not a string but infact an array (what your question indicates) use JSON.
Here is another approach, up to the OP to choose which one he prefers.
When including the code below in the __init__
.py file before any other code, messages printed with print
and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:
import sys
path = "/Users/#username#"
errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog
(for Mac, change #username#
to the name of your user folder. On Windows the path to your user folder will have a different format)
When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella
For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.
The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:
db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:
db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
{$inc : {total : 1 , "items.$.price" : 1}} ,
false ,
true);
Make sure your DataGrid has Width
set to something like {Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window,AncestorLevel=1}}
.
Like that, your setting of Width="*"
attribute on DataGrid.Columns/DataGridXXXXColumn
elements should work.
Also removing the submodule and then running git submodule init
and git submodule update
will obviously do the trick, but may not always be appropriate or possible.
You should append to the container, not the last element:
$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
The append() function should've probably been called add() in jQuery because it sometimes confuses people. You would think it appends something after the given element, while it actually adds it to the element.
Tested in IE7 - 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:
<ul>
<li><li></li>
<li><li></li>
<li><li>
<ul>
<li><li></li>
<li><li></li>
<li><li></li>
<li><li></li>
</ul>
</li>
<li><li></li>
<li><li></li>
<li><li></li>
</ul>
CSS:
* {
margin: 0;
padding: 0;
}
body {
font: 200%/1.5 Optima, 'Lucida Grande', Lucida, 'Lucida Sans Unicode', sans-serif;
}
ul {
width: 9em;
list-style-type: none;
font-size: 0.75em;
}
li {
float: left;
margin: 0 4px 4px 0;
background: #60c;
background: rgba(102, 0, 204, 0.66);
border: 4px solid #60c;
color: #fff;
}
li:hover {
position: relative;
}
ul ul {
z-index: 1;
position: absolute;
left: -999em;
width: auto;
background: #ccc;
background: rgba(204, 204, 204, 0.33);
}
li:hover ul {
top: 2em;
left: 3px;
}
li li {
margin: 0 0 3px 0;
background: #909;
background: rgba(153, 0, 153, 0.66);
border: 3px solid #909;
}
What constitutes, "internal knowledge?" Does knowing that such-and-such algorithm was used to solve a problem qualify or does the tester have to see every line of code for it to be "internal?"
I think in any test case, there should be expected results given by the specification used and not determined by how the tester decides to interpret the specification as this can lead to issues where each thinks they are right and blaming the other for the problem.
Actually you can do it.
Although, someone should note that repeating the CASE
statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE
twice so that you won't get any performance hit because of that.
Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)
INSERT INTO dbo.T1
(
Col1,
Col2,
Col3
)
SELECT
1,
SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
dbo.T1 t
LEFT OUTER JOIN
(
SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1
This will insert the values (1, 2, 3) for each record in the table T1
. This uses a delimiter '%'
to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar
fields etc.). But the main logic is that you should join the CASE
statement and select from the result set of the join with using a split logic.
In Oracle 12c+
, you can use Top n queries along with analytic function rank
to achieve this very concisely without subqueries:
select *
from your_table
order by rank() over (partition by user_id order by my_date desc)
fetch first 1 row with ties;
The above returns all the rows with max my_date per user.
If you want only one row with max date, then replace the rank
with row_number
:
select *
from your_table
order by row_number() over (partition by user_id order by my_date desc)
fetch first 1 row with ties;
In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.
There is a function dedicated for just this purpose, preg_grep
. It will take a regular expression as first parameter, and an array as the second.
See the below example:
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep ('/^hello (\w+)/i', $haystack);
print_r ($matches);
output
Array
(
[1] => hello stackoverflow
[2] => hello world
)
array_reduce
with preg_match
can solve this issue in clean manner; see the snippet below.
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
function _matcher ($m, $str) {
if (preg_match ('/^hello (\w+)/i', $str, $matches))
$m[] = $matches[1];
return $m;
}
// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.
$matches = array_reduce ($haystack, '_matcher', array ());
print_r ($matches);
output
Array
(
[0] => stackoverflow
[1] => world
)
Documentation
array_reduce
seems tedious, isn't there another way?Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_*
or preg_*
function.
Wrap it in a function if you are going to use this method more than once.
$matches = array ();
foreach ($haystack as $str)
if (preg_match ('/^hello (\w+)/i', $str, $m))
$matches[] = $m[1];
Documentation
Or you could simply write:
ng-href="\#yourAnchorId"
Please notice the backslash in front of the hash symbol
From Spring In Action
As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.
In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.
There is a Headers
property in the HttpRequestMessage
class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders
in the HttpClient
class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.
Hope this makes things more clear, at least for someone seeing this answer in future.
You can password protect SQLite3 DB. For the first time before doing any operations, set password as follows.
SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.open();
then next time you can access it like
conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();
This wont allow any GUI editor to view Your data.
Later if you wish to change the password, use conn.ChangePassword("new_password");
To reset or remove password, use conn.ChangePassword(String.Empty);
Many people prefer to use just .keep
since the convention has nothing to do with git.
This answer is likely wrong wrong the context. I thought VBA now run on the CLR these days, but it does not. In any case, this reply may be useful to someone. Or not.
If you run Office 2010 32-bit mode then it's the same as Office 2007. (The "issue" is Office running in 64-bit mode). It's the bitness of the execution context (VBA/CLR) which is important here and the bitness of the loaded VBA/CLR depends upon the bitness of the host process.
Between 32/64-bit calls, most notable things that go wrong are using long
or int
(constant-sized in CLR) instead of IntPtr
(dynamic sized based on bitness) for "pointer types".
The ShellExecute function has a signature of:
HINSTANCE ShellExecute(
__in_opt HWND hwnd,
__in_opt LPCTSTR lpOperation,
__in LPCTSTR lpFile,
__in_opt LPCTSTR lpParameters,
__in_opt LPCTSTR lpDirectory,
__in INT nShowCmd
);
In this case, it is important HWND is IntPtr
(this is because a HWND is a "HANDLE" which is void*
/"void pointer") and not long
. See pinvoke.net ShellExecute as an example. (While some "solutions" are shady on pinvoke.net, it's a good place to look initially).
Happy coding.
As far as any "new syntax", I have no idea.
IN GALAXY Devices :
You need to make sure that you havn't turned it off in the device using the Settings > Developer Options:
As suggested by Adam Miller in the comments, I'll add another solution.
The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:
MailMessage Msg = new MailMessage(fromMail, addresses);
In this particular case, we can replace the ';' for ',' and still make use of the constructor.
MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));
Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.
Using a #t=10,20
fragment worked for me.
Do this to add flutter permanently to your path (in Ubuntu):
cd $HOME
gedit .bashrc
export PATH="$PATH:[location_where_you_extracted_flutter]/flutter/bin"
in the text file and save it.
source $HOME/.bashrc
flutter doctor
commandYou can call .prop("tagName")
. Examples:
jQuery("<a>").prop("tagName"); //==> "A"
jQuery("<h1>").prop("tagName"); //==> "H1"
jQuery("<coolTagName999>").prop("tagName"); //==> "COOLTAGNAME999"
If writing out .prop("tagName")
is tedious, you can create a custom function like so:
jQuery.fn.tagName = function() {
return this.prop("tagName");
};
Examples:
jQuery("<a>").tagName(); //==> "A"
jQuery("<h1>").tagName(); //==> "H1"
jQuery("<coolTagName999>").tagName(); //==> "COOLTAGNAME999"
Note that tag names are, by convention, returned CAPITALIZED. If you want the returned tag name to be all lowercase, you can edit the custom function like so:
jQuery.fn.tagNameLowerCase = function() {
return this.prop("tagName").toLowerCase();
};
Examples:
jQuery("<a>").tagNameLowerCase(); //==> "a"
jQuery("<h1>").tagNameLowerCase(); //==> "h1"
jQuery("<coolTagName999>").tagNameLowerCase(); //==> "cooltagname999"
I had some of my td
s with:
white-space: pre;
This solved it for me:
white-space: pre-wrap;
The correct way to change directories is actually with process.chdir(directory)
. Here's an example from the documentation:
console.log('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
console.log('New directory: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
This is also testable in the Node.js REPL:
[monitor@s2 ~]$ node
> process.cwd()
'/home/monitor'
> process.chdir('../');
undefined
> process.cwd();
'/home'
I had the same exact issue on my ArchLinux VPS today.
mysql -u root -p
just didn't work, whereas mysql -u root -pmypassword
did.
It turned out I had a broken /dev/tty device file (most likely after a udev upgrade), so mysql couldn't use it for an interactive login.
I ended up removing /dev/tty and recreating it with mknod /dev/tty c 5 1
and chmod 666 /dev/tty
. That solved the mysql problem and some other issues too.
In my case, I was getting the error when creating an "MVC 5 Controller with view, using Entity Framework".
I just needed to Build the project after creating the Model class and didn't need to use the [Key] annotation.
Look at the yesno helper
Eg:
{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
I was looking for something along what you wanted, but wanted to put it back into a variable.
So this is what I did
variable = ['hello this is x' x ', this is now y' y ', finally this is d:' d]
basically
variable = [str1 str2 str3 str4 str5 str6]
Another option is to update the Microsoft.AspnNet.Mvc NuGet package. Be careful, because NuGet update does not update the Web.Config. You should update all previous version numbers to updated number. For example if you update from asp.net MVC 4.0.0.0 to 5.0.0.0, then this should be replaced in the Web.Config:
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:
iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP
I have tested your example, and while Request.QueryString is not convertible to a string neither implicit nor explicit still the .ToString() method returns the correct result.
Further more when concatenating with a string using the "+" operator as in your example it will also return the correct result (because this behaves as if .ToString() was called).
As such there is nothing wrong with your code, and I would suggest that your issue was because of a typo in your code writing "Querystring" instead of "QueryString".
And this makes more sense with your error message since if the problem is that QueryString is a collection and not a string it would have to give another error message.
Add the following line at the top of the file that gives the error:
declare var require: any
Although, I'm a big fan of Kanban Tool service (it has everything you need except free of charge) and therefore it's difficult for me to stay objective, I think that should go for Trello or Kanban Flow. Both are free and both provide basic features that are essential for agile process managers and their teams.
I'm no expert but I'd say that if you really want to be semantic, you should use vocabularies (RDFa).
This should result in something like that:
<em property="italic" href="http://url/to/a/definition_of_italic"> Your text </em>
em
is used for the presentation (humans will see it in italic) and the property
and href
attributes are linking to a definition of what italic is (for machines).
You should check if there's a vocabulary for that kind of thing, maybe properties already exist.
More info about RDFa here: http://www.alistapart.com/articles/introduction-to-rdfa/
Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter
@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton
pickle
module is part of the standard library in Python for a very long time now so there is no need to install it via pip
. I wonder if you IDE or command line is not messed up somehow so that it does not find python installation path. Please check if your %PATH%
contains a path to python (e.g. C:\Python36\
or something similar) or if your IDE correctly detects root path where Python is installed.
Above answer can be considered to be confusing a little. String methods are not modifying original object. They return new object. It must be:
var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str
Alternatively, db.rawQuery(sql, selectionArgs) exists.
Cursor c = db.rawQuery(select, null);
This works for me,
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("26/09/2015",ukDtfi).ToString(usDtfi.ShortDatePattern);
i think csrf only works with spring forms
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
change to form:form
tag and see it that works.
It depends, if you are referring to unsigned long the formatting character is "%lu"
. If you're referring to signed long the formatting character is "%ld"
.
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, String
is 0-indexed, i.e. the first character is at index 0
and the last character is at index length() - 1
.
So, assuming getSymbol()
returns a String
, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.
With this prototype you can simply call
.hashCode()
on any string, e.g."some string".hashCode()
, and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) {
return hash;
}
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
Use Come thing link this , This is Based on Bootstrap 3.0
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus {
background-color: #977EBD;
color: #FFFFFF;
}
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
background-color: #977EBD;
color: #FFFFFF;
}
If you have proxy i suggest using SVNGITDownloader it is under .NET Framework and its source code is available
Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?
For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.
Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).
The code has the following issues:
<a4j:commandButton .../>
) does not work with attachments.a4j
tags.<a4j:commandButton .../>
to <h:commandButton .../>
.bw.write( getDomainDocument() );
to bw.write( document );
.String document = getDomainDocument();
to the first line of the try/catch
.<a4j:outputPanel.../>
(not shown) to <h:messages showDetail="false"/>
.Essentially, remove all the Ajax facilities related to the commandButton
. It is still possible to display error messages and leverage the RichFaces UI style.
In my case, I was getting the error with Mac OS X 10.9 Mavericks. I installed MySQL Community Server directly from the Oracle/MySQL Website from DMG.
All I needed to do was symlink the lib files to the /usr/local/lib directory.
mkdir -p /usr/local/lib
ln -s /usr/local/mysql/lib/libmysql* /usr/local/lib
Bonus: If you're running Mac OS X as well, there is a great tool to finding files like the libmysqlclient.18.dylib file, http://apps.tempel.org/FindAnyFile. This is how I originally found the location of the dylib file.
By default, Windows associates .js
files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js
file in Explorer), the script is executed by wscript.exe
.
This may be solving a local problem with a global setting, but you could associate .js
files with node.exe
instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.
Of course, if—like me—you've associated .js
files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js
files, although this alternative doesn't solve your command-line needs.
The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:
"C:\Program Files (x86)\nodejs\node.exe" app.js %*
Another alternative is this very simple C# app which will start Node using its own filename + .js
as the script to run, and pass along any command line arguments.
class Program
{
static void Main(string[] args)
{
var info = System.Diagnostics.Process.GetCurrentProcess();
var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
proc.UseShellExecute = false;
System.Diagnostics.Process.Start(proc);
}
}
So if you name the resulting EXE "app.exe", you can type app arg1 ...
and Node will be started with the command line "app.js" arg1 ...
. Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.
Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.
I am assuming you are not using Json.NET (Newtonsoft.Json NuGet package). If this the case, then you should try it.
It has the following features:
JsonIgnore
and JsonProperty
can be added to a class to customize how a class is serializedLook at the example below. In this example, JsonConvert
class is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj)
and DeserializeObject<T>(String json)
:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
You would write a comparator class, for example:
struct CompareAge {
bool operator()(Person const & p1, Person const & p2) {
// return "true" if "p1" is ordered before "p2", for example:
return p1.age < p2.age;
}
};
and use that as the comparator argument:
priority_queue<Person, vector<Person>, CompareAge>
Using greater
gives the opposite ordering to the default less
, meaning that the queue will give you the lowest value rather than the highest.
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
I tried this and worked for me.
Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds
1- Register the notification in the viewWillAppear
method:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
2- Method to be called:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
print(keyboardHeight)
}
}
If you want to know if it's an empty string use === instead of ==.
if(variable === "") {
}
This is because === will only return true if the values on both sides are of the same type, in this case a string.
for example: (false == "") will return true, and (false === "") will return false.
A good rule of thumb: use the built-in help system in Python. Example below...
jdoe@server:~$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)
------------------------------------------
NAME
memcache - client module for memcached (memory cache daemon)
FILE
/usr/lib/python2.7/dist-packages/memcache.py
MODULE DOCS
http://docs.python.org/library/memcache
DESCRIPTION
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
...
------------------------------------------
I wanted to have multiple datasources in the app config. So after setting up a section in the app.config i swaped out the datasource and then pass it into the dbcontext as the connection string.
//Get the key/value connection string from app config
var sect = (NameValueCollection)ConfigurationManager.GetSection("section");
var val = sect["New DataSource"].ToString();
//Get the original connection string with the full payload
var entityCnxStringBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["OriginalStringBuiltByADO.Net"].ConnectionString);
//Swap out the provider specific connection string
entityCnxStringBuilder.ProviderConnectionString = val;
//Return the payload with the change in connection string.
return entityCnxStringBuilder.ConnectionString;
This took me a bit to figure out. I hope it helps someone out. I was making it way too complicated. before this.
I went to menu: Tools → Options.
Environment → Keyboard.
Show command containing and searched: comment
I changed Edit.CommentSelection and assigned Ctrl+/ for commenting.
And I left Ctrl+K then U for the Edit.UncommentSelection.
These could be tweaked to the user's preference as to what key they would prefer for commenting/uncommenting.