In this solution you do not need to take static variable;
Button nextBtn;
private SupportMapFragment mMapFragment;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (mRootView != null) {
ViewGroup parent = (ViewGroup) mRootView.getParent();
Utility.log(0,"removeView","mRootView not NULL");
if (parent != null) {
Utility.log(0, "removeView", "view removeViewed");
parent.removeAllViews();
}
}
else {
try {
mRootView = inflater.inflate(R.layout.dummy_fragment_layout_one, container, false);//
} catch (InflateException e) {
/* map is already there, just return view as it is */
e.printStackTrace();
}
}
return mRootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.mapView);
if (mapFragment == null) {
mapFragment = new SupportMapFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.mapView, mapFragment, "mapFragment");
ft.commit();
fm.executePendingTransactions();
}
//mapFragment.getMapAsync(this);
nextBtn = (Button) view.findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Utility.replaceSupportFragment(getActivity(),R.id.dummyFragment,dummyFragment_2.class.getSimpleName(),null,new dummyFragment_2());
}
});
}`
Steps:
android.library.reference.1=google-play-services_lib
YOUR_PROJECT/proguard-project.txt
.
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
Now you are ready to create your own Google Map app with using Google Map APIs V2 for Android.
If you create application with min SDK = 8, please use android support library v4 + SupportMapFragment instead of MapFragment.
With ui-router this may be an option for you. It reloads the controller on close so reinitializes the modal contents before it fires next time.
$("#myModalId").on('hidden.bs.modal', function () {
$state.reload(); //resets the modal
});
Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH
If you need to specify the exact charactor length, we have to avoid values with 0 in-front.
Final String representation must have that exact character length.
String GenerateRandomNumber(int charLength) {
return String.valueOf(charLength < 1 ? 0 : new Random()
.nextInt((9 * (int) Math.pow(10, charLength - 1)) - 1)
+ (int) Math.pow(10, charLength - 1));
}
The ngRoute module is no longer part of the core angular.js
file. If you are continuing to use $routeProvider then you will now need to include angular-route.js
in your HTML:
<script src="angular.js">
<script src="angular-route.js">
You also have to add ngRoute
as a dependency for your application:
var app = angular.module('MyApp', ['ngRoute', ...]);
If instead you are planning on using angular-ui-router
or the like then just remove the $routeProvider
dependency from your module .config()
and substitute it with the relevant provider of choice (e.g. $stateProvider
). You would then use the ui.router
dependency:
var app = angular.module('MyApp', ['ui.router', ...]);
You also need to configure and start the MySQL server. This will probably help
As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.
So as on the above question I have putted my basic efforts.
Function multi_add(a As Range, ParamArray b() As Variant) As Double
Dim ele As Variant
Dim i As Long
For Each ele In a
multi_add = a + ele.Value **- a**
Next ele
For i = LBound(b) To UBound(b)
For Each ele In b(i)
multi_add = multi_add + ele.Value
Next ele
Next i
End Function
- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.
select segment_name as tablename, sum(bytes/ (1024 * 1024 * 1024)) as tablesize_in_GB
From dba_segments /* if looking at tables not owned by you else use user_segments */
where segment_name = 'TABLE_WHOSE_SIZE_I_WANT_TO_KNOW'
and OWNER = 'WHO OWNS THAT TABLE' /* if user_segments is used delete this line */
group by segment_name ;
Rounding up to the next 0.05, I would do this way:
def roundup(x):
return round(int(math.ceil(x / 0.05)) * 0.05,2)
If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.
The Jenkins CLI supports listing all installed plugins:
java -jar jenkins-cli.jar -s http://localhost:8080/ list-plugins
I use the __super keyword. But it's Microsoft specific:
This is an improvement of the most upvoted solution by Antonio Max, which also works with XML that has namespaces (by replacing the colon with an underscore). It also has some extra options (and does parse <person my-attribute='name'>John</person>
correctly).
function parse_xml_into_array($xml_string, $options = array()) {
/*
DESCRIPTION:
- parse an XML string into an array
INPUT:
- $xml_string
- $options : associative array with any of these keys:
- 'flatten_cdata' : set to true to flatten CDATA elements
- 'use_objects' : set to true to parse into objects instead of associative arrays
- 'convert_booleans' : set to true to cast string values 'true' and 'false' into booleans
OUTPUT:
- associative array
*/
// Remove namespaces by replacing ":" with "_"
if (preg_match_all("|</([\\w\\-]+):([\\w\\-]+)>|", $xml_string, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$xml_string = str_replace('<'. $match[1] .':'. $match[2], '<'. $match[1] .'_'. $match[2], $xml_string);
$xml_string = str_replace('</'. $match[1] .':'. $match[2], '</'. $match[1] .'_'. $match[2], $xml_string);
}
}
$output = json_decode(json_encode(@simplexml_load_string($xml_string, 'SimpleXMLElement', ($options['flatten_cdata'] ? LIBXML_NOCDATA : 0))), ($options['use_objects'] ? false : true));
// Cast string values "true" and "false" to booleans
if ($options['convert_booleans']) {
$bool = function(&$item, $key) {
if (in_array($item, array('true', 'TRUE', 'True'), true)) {
$item = true;
} elseif (in_array($item, array('false', 'FALSE', 'False'), true)) {
$item = false;
}
};
array_walk_recursive($output, $bool);
}
return $output;
}
The first one is the default object constructor call. You can use it's parameters if you want.
var array = new Array(5); //initialize with default length 5
The second one gives you the ability to create not empty array:
var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
I found the answer by @Blairg23 working , after the following correction (covering the scenario where it failed to work correctly):
for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a')):
if link.has_attr('href'):
if file_type in link['href']:
full_path =urlparse.urljoin(url , link['href']) #module urlparse need to be imported
wget.download(full_path)
For Python 3:
urllib.parse.urljoin
has to be used in order to obtain the full URL instead.
For those who don't know about Clockwise/Spiral Rule: Start from the name of the variable, move clockwisely (in this case, move backward) to the next pointer or type. Repeat until expression ends.
Here is a demo:
Try casting the ints to varchar, before adding them to a string:
SET @ActualWeightDIMS = cast(@Actual_Dims_Lenght as varchar(8)) +
'x' + cast(@Actual_Dims_Width as varchar(8)) +
'x' + cast(@Actual_Dims_Height as varhcar(8))
I'm using this script by Adam Anderson, updated to support objects in other schemas than dbo.
declare @n char(1)
set @n = char(10)
declare @stmt nvarchar(max)
-- procedures
select @stmt = isnull( @stmt + @n, '' ) +
'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures
-- check constraints
select @stmt = isnull( @stmt + @n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.check_constraints
-- functions
select @stmt = isnull( @stmt + @n, '' ) +
'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )
-- views
select @stmt = isnull( @stmt + @n, '' ) +
'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views
-- foreign keys
select @stmt = isnull( @stmt + @n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys
-- tables
select @stmt = isnull( @stmt + @n, '' ) +
'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables
-- user defined types
select @stmt = isnull( @stmt + @n, '' ) +
'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1
exec sp_executesql @stmt
I would use a composite (multi-column) key.
CREATE TABLE INFO (
t1ID INT,
t2ID INT,
PRIMARY KEY (t1ID, t2ID)
)
This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.
Answering my question based on the suggestions from Maudicus and Hit.
Check the WebView tutorial here. Just implement the web client and set it before loadUrl. The simplest way is:
myWebView.setWebViewClient(new WebViewClient());
For more advanced processing for the web content, consider the ChromeClient.
With docker compose there's a simple alternative (no need to create a Dockerfile). Just create a init-database.sh:
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER docker;
CREATE DATABASE my_project_development;
GRANT ALL PRIVILEGES ON DATABASE my_project_development TO docker;
CREATE DATABASE my_project_test;
GRANT ALL PRIVILEGES ON DATABASE my_project_test TO docker;
EOSQL
And reference it in the volumes section:
version: '3.4'
services:
postgres:
image: postgres
restart: unless-stopped
volumes:
- postgres:/var/lib/postgresql/data
- ./init-database.sh:/docker-entrypoint-initdb.d/init-database.sh
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
volumes:
postgres:
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
If you are java 1.6 then the following can also be done:
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class CompilerExample {
public static void main(String[] args) {
String fileToCompile = "/Users/rupas/VolatileExample.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
}
}
Use the below code to solve the CertPathValidatorException issue.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(YOUR_BASE_URL)
.client(getUnsafeOkHttpClient().build())
.build();
public static OkHttpClient.Builder getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return builder;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
For more details visit https://mobikul.com/android-retrofit-handling-sslhandshakeexception/
I came across the same issue whilst resuming work on a old MEAN stack project. I was using nodemon
as my local development server and got the same error Resource interpreted as stylesheet but transferred with MIME type text/html
. I changed from nodemon
to http-server
which can be found here. It immediately worked for me.
If each pixel is assumed to be of the same area then the following article about converting distances to longitude/latitude co-ordinates may be of some help to you:
http://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/
Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag
Example:
<video controls="controls" width="800" height="600"
name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>
This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)
Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)
Try replacing the appropriate lines with:
myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";
Your code is incorrect because the sub-arrays have a length of y
, and indexing starts at 0. So setting to myStringArray[0][y]
or myStringArray[0][x]
will fail because the indices x
and y
are out of bounds.
String[][] myStringArray = new String [x][y];
is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
I think there is some difficulty using the "NUL" tecnique when there are SPACES in the directory name, such as "Documents and Settings."
I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe
Here are some examples of what DID NOT work and what DOES WORK for me:
(These are all demonstrations done "live" at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)
This DID NOT work:
D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes
This DID NOT work:
D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes
This DOES work (for me):
D:\Documents and Settings>cd ..
D:\>REM get the short 8.3 name for the file
D:\>dir /x
Volume in drive D has no label.
Volume Serial Number is 34BE-F9C9
Directory of D:\
09/25/2008 05:09 PM <DIR> 2008
09/25/2008 05:14 PM <DIR> 200809~1.25 2008.09.25
09/23/2008 03:44 PM <DIR> BOOST_~3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME~1.EXE ChromeSetup.exe
02/14/2008 12:32 PM <DIR> cygwin
[[Look right here !!!! ]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings
09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM <DIR> NATION~1 National Instruments Downloads
10/12/2007 11:25 AM <DIR> NVIDIA
05/13/2008 09:42 AM <DIR> Office10
09/19/2008 11:08 AM <DIR> PROGRA~1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM <DIR> TEMP
02/14/2008 12:26 PM <DIR> tmp
01/21/2008 07:05 PM <DIR> VXIPNP
09/23/2008 12:15 PM <DIR> WINDOWS
02/21/2008 03:49 PM <DIR> wx28
02/29/2008 01:47 PM <DIR> WXWIDG~2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free
D:\>REM now use the \NUL test with the 8.3 name
D:\>if exist d:\docume~1\NUL echo yes
yes
This works, but it's sort of silly, because the dot already implies i am in a directory:
D:\Documents and Settings>if exist .\NUL echo yes
If you've exported the environment variable:
export demoPath=/usr/local/demo
you can simply refer to it by name in the makefile
(make
imports all the environment variables you have set):
DEMOPATH = ${demoPath} # Or $(demoPath) if you prefer.
If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:
make DEMOPATH="${demoPath}" …
If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo
for the export
command.
It should be exclude module: 'net.milkbowl:vault:1.2.27'
(add module:
) as explained in documentation for DependencyHandler
linked from http://www.gradle.org/docs/current/javadoc/org/gradle/api/Project.html#dependencies(groovy.lang.Closure) because ModuleDependency.exclude(java.util.Map)
method is used.
In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged
event:
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
// To work around this, we create the binding once we get the viewmodel through the datacontext.
var newViewModel = e.NewValue as MyViewModel;
var executablePathBinding = new Binding
{
Source = newViewModel,
Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
};
BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}
We have also had cases were we just saved the DataContext
to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext
around, I think it would be nice to also call:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
to clear the binding of the old viewmodel (e.oldValue
in the event handler).
Try this function
getQuantileGroupNum <- function(vec, group_num, decreasing=FALSE) {
if(decreasing) {
abs(cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T) - group_num - 1)
} else {
cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T)
}
}
> t1 <- runif(7)
> t1
[1] 0.4336094 0.2842928 0.5578876 0.2678694 0.6495285 0.3706474 0.5976223
> getQuantileGroupNum(t1, 4)
[1] 2 1 3 1 4 2 4
> getQuantileGroupNum(t1, 4, decreasing=T)
[1] 3 4 2 4 1 3 1
The illegal character is not in $matches[1]
, but in $xml
Try
iconv($matches[1], 'utf-8//TRANSLIT', $xml);
And showing us the input string would be nice for a better answer.
View mView;
mView.getContext();
Update : STYLE GUIDE is now on Angular docs.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.
The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.
- John Papa
Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide
Just wanted to say that after I installed the Intel HAXM accelerator and use the Intel Atom image the emulator seems to run 50 times faster. The difference is amazing, check it out!
http://www.developer.com/ws/android/development-tools/haxm-speeds-up-the-android-emulator.html
Unless you need more than just the contents of the file, you could use file_get_contents
.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.
This is how you can achieve this.
upstream {
nodeapp 127.0.0.1:8080;
}
server {
listen 80;
# The host name to respond to
server_name cdn.domain.com;
location /(.*) {
proxy_pass http://nodeapp/$1$is_args$args;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Real-Port $server_port;
proxy_set_header X-Real-Scheme $scheme;
}
}
You can also use this configuration to load balance amongst multiple Node processes like so:
upstream {
nodeapp 127.0.0.1:8081;
nodeapp 127.0.0.1:8082;
nodeapp 127.0.0.1:8083;
}
Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.
The document
and window
are different objects and they have some different events. Using addEventListener()
on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a "resize"
event on the window
object that is not on the document
object.
For example, the "DOMContentLoaded"
event is only on the document
object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener()
on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document
object before the window
object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document
over window
when either will work. But, I'd often move even closer to the source and use document.body
or even some closer common parent in the document (if possible).
Just do myFunction.foo = "bar"
and it will add it. myFunction
is the name of the object in this case.
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
You can use
$_FILES['filename']['error'];
If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done
1 : if file size is over limit .... You can find other options by googling
SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...
I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)
You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.
If you don't like VBA, btw, you can do the same using VB.NET or C#.
[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]
I found this approach useful. This way you do not need a class nor final
btnInsert.addMouseListener(new MouseAdapter() {
private Statement _statement;
public MouseAdapter setStatement(Statement _stmnt)
{
_statement = _stmnt;
return this;
}
@Override
public void mouseDown(MouseEvent e) {
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try {
_statement.executeUpdate(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}.setStatement(statement));
If the size of the string is fixed, you might find easier to use an array of chars. If you have to do this a lot, it will be a tiny bit faster too.
char[] chars = new char[3];
chars[0] = 'i';
chars[1] = 'c';
chars[2] = 'e';
return new String(chars);
Also, I noticed in your original question, you use the Char class. If your chars are not nullable, it is better to use the lowercase char type.
An example using CSS
ul li:not(:last-child){
border-right: 1px solid rgba(153, 151, 151, 0.75);
}
they are some needs i can't see to dome thing like Keith or Marcos Placona did instead of just doing
using System;
using System.Windows.Forms;
namespace WFsimulateMouseClick
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1_Click(button1, new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 1, 1, 1));
//by the way
//button1.PerformClick();
// and
//button1_Click(button1, new EventArgs());
// are the same
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("clicked");
}
}
}
If you have to do group by
using hibernate criteria use projections.groupPropery
like the following,
@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
Works fine for me, please try:
.scroll-container {
max-height: 250px;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
Hi I followed following steps and I had been able to get the refresh token.
Authorization flow has two steps.
Is to obtain the authorization code using https://accounts.google.com/o/oauth2/auth?
URL.
For that a post request is sent providing following parameters. 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE + '&access_type=offline'
Providing above will receive a authorization code.
Retrieving AcessToken and RefreshToken using https://accounts.google.com/o/oauth2/token?
URL.
For that a post request is sent providing following parameters.
"code" : code, "client_id" : CID, "client_secret" : CSECRET, "redirect_uri" : REDIRECT, "grant_type" : "authorization_code",
So in your first attempt once you authorize the permissions you will be able to get the Refresh token. Subsequent attempts will not provide the refresh token. If you want the token again the revoke the access in you application.
Hope this will help someone cheers :)
Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'
This will give you all the row which contains any special character.
$_FILES["file"]["name"] - the name of the uploaded file
Using a list comprehension:
from datetime import date, timedelta
d1 = date(2008,8,15)
d2 = date(2008,9,15)
# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]
for d in dd:
print d
# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)
var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD = Math.abs(Math.floor(total/1000));
var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);
var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";
document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
Here's my two cent's worth: I've previously implemented an IdFactory
class that created IDs in the format [host name]-[application start time]-[current time]-[discriminator]. This largely guaranteed that IDs were unique across JVM instances whilst keeping the IDs readable (albeit quite long). Here's the code in case it's of any use:
public class IdFactoryImpl implements IdFactory {
private final String hostName;
private final long creationTimeMillis;
private long lastTimeMillis;
private long discriminator;
public IdFactoryImpl() throws UnknownHostException {
this.hostName = InetAddress.getLocalHost().getHostAddress();
this.creationTimeMillis = System.currentTimeMillis();
this.lastTimeMillis = creationTimeMillis;
}
public synchronized Serializable createId() {
String id;
long now = System.currentTimeMillis();
if (now == lastTimeMillis) {
++discriminator;
} else {
discriminator = 0;
}
// creationTimeMillis used to prevent multiple instances of the JVM
// running on the same host returning clashing IDs.
// The only way a clash could occur is if the applications started at
// exactly the same time.
id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
lastTimeMillis = now;
return id;
}
public static void main(String[] args) throws UnknownHostException {
IdFactory fact = new IdFactoryImpl();
for (int i=0; i<1000; ++i) {
System.err.println(fact.createId());
}
}
}
The working solution for Integer number to binary conversion is below.
int main()
{
int num=241; //Assuming 16 bit integer
for(int i=15; i>=0; i--) cout<<((num >> i) & 1);
cout<<endl;
for(int i=0; i<16; i++) cout<<((num >> i) & 1);
cout<<endl;
return 0;
}
You can capture the cout<< part based on your own requirement.
My problem was that I was trying to connect from a version of mysql client that seems to be incompatible with the mysql server I installed (mysql:latest which installed version 8.0.22 at the time of this writing).
my mysql client version:
$ mysql --version
mysql Ver 14.14 Distrib 5.7.26, for Linux (x86_64) using EditLine wrapper
The docker command that I used to install mysql:latest:
$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=somerootpassword -e MYSQL_USER=someuser -e MYSQL_PASSWORD=someuserpassword -d -p 3306:3306 mysql:latest
The errors I got when connecting from my local mysql client to the mysql server:
$ mysql -u someuser -p -h 127.0.0.1
ERROR 2026 (HY000): SSL connection error: unknown error number
(sometimes I would get another error: "ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 2". But I think this happens when I try to connect to the server too early after I started it)
My solution was to install mysql:5.7 instead:
$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=somerootpassword -e MYSQL_USER=someuser -e MYSQL_PASSWORD=someuserpassword -d -p 3306:3306 mysql:5.7
and then I can connect to the server (after waiting perhaps 1 minute until the server is ready to accept connections):
$ mysql -u someuser -p -h 127.0.0.1
The results = 'hide'
option doesn't prevent other messages to be printed.
To hide them, the following options are useful:
{r, error=FALSE}
{r, warning=FALSE}
{r, message=FALSE}
In every case, the corresponding warning, error or message will be printed to the console instead.
The delete
operator deallocates memory and calls the destructor for a single object created with new
.
The delete []
operator deallocates memory and calls destructors for an array of objects created with new []
.
Using delete
on a pointer returned by new []
or delete []
on a pointer returned by new
results in undefined behavior.
NOTE: This answer addresses enterprise-class development in-the-large.
This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.
In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.
Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.
The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.
I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.
In a word, you can't.
3.65
cannot be represented exactly as a float
. The number that you're getting is the nearest number to 3.65
that has an exact float
representation.
The difference between (older?) Python 2 and 3 is purely due to the default formatting.
I am seeing the following both in Python 2.7.3 and 3.3.0:
In [1]: 3.65
Out[1]: 3.65
In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
For an exact decimal datatype, see decimal.Decimal
.
If you are unsure of the size of the array or if it can change you can do this to have a static array.
ArrayList<Player> thePlayersList = new ArrayList<Player>();
thePlayersList.add(new Player(1));
thePlayersList.add(new Player(2));
.
.
//Some code here that changes the number of players e.g
Players[] thePlayers = thePlayersList.toArray();
Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.
Lazy loading images by attaching listener to scroll events or by making use of setInterval is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.
Use Lozad.js (just 569 bytes with no dependencies), which uses IntersectionObserver to lazy load images performantly.
You can try this:
<a href="link.html">
<input type="button" value="Visit Page" />
</a>
This will create button inside a link and it works on any browser
This works for me:
psql -h localhost -U postgres
my best solution :
WHERE
COALESCE(char_length(fieldValue), 0) = 0
COALESCE returns the first non-null expr in the expression list().
if the fieldValue is null or empty string then: we will return the second element then 0.
so 0 is equal to 0 then this fieldValue is a null or empty string.
in python for exemple:
def coalesce(fieldValue):
if fieldValue in (null,''):
return 0
good luck
clear project and then run. it will work
For macOS catalina try this : open Xcode. if not existing. download from App store (about 11GB) then open Xcode>open developer tool>more developer tool and used my apple id to download a compatible command line tool. Then, after downloading, I opened Xcode>Preferences>Locations>Command Line Tool and selected the newly downloaded command line tool from downloads.
You need to set the flags after the project
command in your CMakeLists.txt.
Also, if you're calling include(${QT_USE_FILE})
or add_definitions(${QT_DEFINITIONS})
, you should include these set
commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")
Date
/Calendar
/SimpleDateFormat
classes.Example:
ZonedDateTime // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now( // Capture the current moment.
ZoneId.of( "Africa/Tunis" ) // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo( // Lop off finer part of this value.
ChronoUnit.MILLIS // Specify level of truncation via `ChronoUnit` enum object.
) // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format( // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // This standard ISO 8601 format is close to your desired output.
) // Returns a `String`.
.replace( "T" , " " ) // Replace `T` in middle with a SPACE.
The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar
& SimpleDateFormat
.
want current date and time
Capture the current moment in UTC using Instant
.
Instant instant = Instant.now() ;
To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Or, as a shortcut, pass a ZoneId
to the ZonedDateTime.now
method.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;
The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit
enum object.
ZonedDateTime
.now(
ZoneId.of( "Pacific/Auckland" )
)
.truncatedTo(
ChronoUnit.MILLIS
)
in “dd/MM/yyyy HH:mm:ss.SS” format
I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.
But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T
where you want a SPACE.
String output =
zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
;
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
Never exchange date-time values using text intended for presentation to humans.
Instead, use the standard formats defined for this very purpose, found in ISO 8601.
The java.time use these ISO 8601 formats by default when parsing/generating strings.
Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant
in java.time. You can exchange a Instant
from a ZonedDateTime
, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.
Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;
2018-01-23T01:23:45.123456789Z
This ISO 8601 format uses a Z
on the end to represent UTC, pronounced “Zulu”.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,
df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')
Read more about the repartition function Read more about the save function
However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.
Read more on repartition vs coalesce functions.
There are two branches to this question (Rolling back a commit does not mean I want to lose all my local changes):
1. To revert the latest commit and discard changes in the committed file do:
git reset --hard HEAD~1
2. To revert the latest commit but retain the local changes (on disk) do:
git reset --soft HEAD~1
This (the later command) will take you to the state you would have been if you did git add
.
If you want to unstage the files after that, do
git reset
Now you can make more changes before adding and then committing again.
Also, if anyone else has the "find: missing argument to -exec" this might help:
In some shells you don't need to do the escaping, i.e. you don't need the "\" in front of the ";".
find <file path> -name "myFile.*" -exec rm - f {} ;
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
When do you choose functional programming over object oriented?
When you anticipate a different kind of software evolution:
Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.
Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.
When evolution goes the wrong way, you have problems:
Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.
Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.
This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem". Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.
What are the typical problem definitions where functional programming is a better choice?
Functional languages excel at manipulating symbolic data in tree form. A favorite example is compilers, where source and intermediate languages change seldom (mostly the same things), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.
You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.
The issue is with the h1
header margin. You need to try this:
h1 {
margin-top:0;
}
Use .unshift()
to add to the beginning of an array.
TheArray.unshift(TheNewObject);
See MDN for doc on unshift()
and here for doc on other array methods.
FYI, just like there's .push()
and .pop()
for the end of the array, there's .shift()
and .unshift()
for the beginning of the array.
(You should you as Else-If
statement to check the for the three different state (positive, negative, 0)
Here is a simple example (excludes the possibility of non-integer values)
import java.util.Scanner;
public class Compare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is equal to zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
}
}
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
%0|%0
is a fork bomb. It will spawn another process using a pipe |
which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).
%0
refers to the command used to run the current program. For example, script.bat
A pipe |
symbol will make the output or result of the first command sequence as the input for the second command sequence. In the case of a fork bomb, there is no output, so it will simply run the second command sequence without any input.
Expanding the example, %0|%0
could mean script.bat|script.bat
. This runs itself again, but also creating another process to run the same program again (with no input).
i also ran into this problem due to syntax error. Using "(" instead of "[" in array index:
foreach($arr_parameters as $arr_key=>$arr_value) {
$arr_named_parameters(":$arr_key") = $arr_value;
}
Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this
can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x
when you really meant to be referring to x
instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.
For me it was another problem. This might be trivial for some, but it took me a while to figure out. So this answer might be helpfull to some.
I had my API_BASE_URL
set to localhost:58577
. The coin dropped after reading the error message for the millionth time. The problem is in the part where it says that it only supports HTTP
and some other protocols. I had to change the API_BASE_URL
so that it includes the protocol. So changing API_BASE_URL
to http://localhost:58577
it worked perfectly.
I used numpy library and it works fine for me. Its just a single line and easy to understand. The input needs to be in a single size separated by space and the reshape converts the list into shape you want. Here (2,2) resizes the list of 4 elements into 2*2 matrix. Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.
import numpy as np
a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)
print(a)
Input
array([[1, 2],
[3, 4]])
Output
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345 1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
$this->db->where('`id` IN (SELECT `someId` FROM `anotherTable` WHERE `someCondition`='condition')', NULL, FALSE);
In projects that use the Gradle build system, what you want to change is the applicationId
in the build.gradle file. The build system uses this value to override anything specified by hand in the manifest file when it does the manifest merge and build.
For example, your module's build.gradle file looks something like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
// CHANGE THE APPLICATION ID BELOW
applicationId "com.example.fred.myapplication"
minSdkVersion 10
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
}
applicationId
is the name the build system uses for the property that eventually gets written to the package
attribute of the manifest
tag in the manifest file. It was renamed to prevent confusion with the Java package name (which you have also tried to modify), which has nothing to do with it.
Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.
The variable Random
is only "in scope" inside the main
method. It's not accessible to any methods called by main
. When you return from main
, the variable disappears (it's part of the stack frame).
If you want all of the methods of your class to use the same Random
instance, declare a member variable:
class MyObj {
private final Random random = new Random();
public void compTurn() {
while (true) {
int a = random.nextInt(10);
if (possibles[a] == 1)
break;
}
}
}
I use this function datetime_to_local_timezone()
, which seems overly convoluted but I found no simpler version of a function that converts a datetime
instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:
import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))
This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:
2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00
both option are valid and targeting two different steps of your build:
file(COPY ...
copies the file in configuration step and only in this step. When you rebuild your project without having changed your cmake configuration, this command won't be executed.add_custom_command
is the preferred choice when you want to copy the file around on each build step. The right version for your task would be:
add_custom_command(
TARGET foo POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_SOURCE_DIR}/test/input.txt
${CMAKE_CURRENT_BINARY_DIR}/input.txt)
you can choose between PRE_BUILD
, PRE_LINK
, POST_BUILD
best is you read the documentation of add_custom_command
an example on how to use the first version can be found here: Use CMake add_custom_command to generate source for another target
Add the jar files on class path NOT modulepath.
This will give you the full name of the month.
select datename(month, S0.OrderDateTime)
If you only want the first three letters you can use this
select convert(char(3), S0.OrderDateTime, 0)
You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
var bks: Book[] = [];
bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"}); //This is all done in JSON.
You can use SQLAlchemy's or_
function to search in more than one column (the underscore is necessary to distinguish it from Python's own or
).
Here's an example:
from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
User.lastname.like(searchVar)))
use jquery
$("#item").change(function({
var x=$(this).val();
});
Your value will be in x
variable, use this variable value in your jsp, like this {x}
this statement will give the value
This question was linked from this blog post and an alternative solution was proposed for the newer versions of Git:
git branch -m master old_master
git checkout --orphan master
git branch -D old_master
This solution assumes that:
master
branchold_master
so I'm free to use that nameIt will rename the existing branch to old_master
and create a new, orphaned, branch master
(like it is created for new repositories) after which you can freely delete old_master
... or not. Up to you.
Note: Moving or copying a git branch preserves its reflog (see this code) while deleting and then creating a new branch destroys it. Since you want to get back to the original state with no history you probably want to delete the branch, but others may want to consider this small note.
The trick is to use useradd
instead of its interactive wrapper adduser
.
I usually create users with:
RUN useradd -ms /bin/bash newuser
which creates a home directory for the user and ensures that bash is the default shell.
You can then add:
USER newuser
WORKDIR /home/newuser
to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser
:
docker run -t -i image
newuser@131b7ad86360:~$
You might have to give newuser
the permissions to execute the programs you intend to run before invoking the user command.
Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.
I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.
Not really. Your padding is (probably) being applied to the list item, so will only affect the actual content within the list item.
Using a combination of background and padding styles can create something that looks similar e.g.
li {
background: url(images/bullet.gif) no-repeat left top; /* <-- change `left` & `top` too for extra control */
padding: 3px 0px 3px 10px;
/* reset styles (optional): */
list-style: none;
margin: 0;
}
You might be looking to add styling to the parent list container (ul) to position your bulleted list items, this A List Apart article has a good starting reference.
Node is used to represent tags in general. Divided to 3 types:
Attribute Note: is node which inside its has attributes.
Exp: <p id=”123”></p>
Text Node: is node which between the opening and closing its have contian text content.
Exp: <p>Hello</p>
Element Node : is node which inside its has other tags.
Exp: <p><b></b></p>
Each node may be types simultaneously, not necessarily only of a single type.
Element is simply a element node.
$("#myframe").load(function() {
alert("loaded");
});
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
I tried to optimize solution by handling user input exceptions.
public class Solution {
private static Integer TERMINATION_VALUE = 0;
public static void main(String[] args) {
Integer value = null;
Integer minimum = Integer.MAX_VALUE;
Integer maximum = Integer.MIN_VALUE;
Scanner scanner = new Scanner(System.in);
while (value != TERMINATION_VALUE) {
Boolean inputValid = Boolean.TRUE;
try {
System.out.print("Enter a value: ");
value = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Value must be greater or equal to " + Integer.MIN_VALUE + " and less or equals to " + Integer.MAX_VALUE );
inputValid = Boolean.FALSE;
scanner.next();
}
if(Boolean.TRUE.equals(inputValid)){
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
}
if(TERMINATION_VALUE.equals(minimum) || TERMINATION_VALUE.equals(maximum)){
System.out.println("There is not any valid input.");
} else{
System.out.println("Minimum: " + minimum);
System.out.println("Maximum: " + maximum);
}
scanner.close();
}
}
If you want to style the browsers standard music player in the CSS:
audio {
enter code here;
}
I'm sorry, I managed to find the answer myself using google and a bit of luck : )
For those interested;
I installed the pdftk (pdf toolkit) on our debian server, and using the following command I achieved desired output:
pdftk file1.pdf file2.pdf cat output output.pdf
OR
gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf ...
This in turn can be piped directly into pdf2ps.
There are two attributes, namely readonly
and disabled
, that can make a semi-read-only input. But there is a tiny difference between them.
<input type="text" readonly />
<input type="text" disabled />
readonly
attribute makes your input text disabled, and users are not able to change it anymore.disabled
attribute make your input-text disabled(unchangeable) but also cannot it be submitted.jQuery approach (1):
$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);
jQuery approach (2):
$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");
JavaScript approach:
document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;
PS disabled
and readonly
are standard html attributes. prop
introduced with jQuery 1.6
.
You can use the following steps:
Step 1: Create a requirements.txt with list of packages to be installed. If you want to copy packages in a particular environment, do this
pip freeze >> requirements.txt
else store package names in a file named requirements.txt
Step 2: Execute pip command with this file
pip install -r requirements.txt
if I want to query all record at some condition,I can use this:
if (userId == 'admin')
userId = {'$regex': '.*.*'};
User.where('status', 1).where('creator', userId);
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
It labels whatever input is the parameter for the for
attribute.
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
This is likely when you have a PRIMARY KEY field and you are inserting a value that is duplicating or you have the INSERT_IDENTITY flag set to on
I'm guessing @sehe's approach is stronger, but until I understand it better, I find myself leap-frogging off of @MichaelSander's extension. I modified it to match the syntax and return type of the built-in Enumerable.Join() method described here. I appended the "distinct" suffix in respect to @cadrell0's comment under @JeffMercado's solution.
public static class MyExtensions {
public static IEnumerable<TResult> FullJoinDistinct<TLeft, TRight, TKey, TResult> (
this IEnumerable<TLeft> leftItems,
IEnumerable<TRight> rightItems,
Func<TLeft, TKey> leftKeySelector,
Func<TRight, TKey> rightKeySelector,
Func<TLeft, TRight, TResult> resultSelector
) {
var leftJoin =
from left in leftItems
join right in rightItems
on leftKeySelector(left) equals rightKeySelector(right) into temp
from right in temp.DefaultIfEmpty()
select resultSelector(left, right);
var rightJoin =
from right in rightItems
join left in leftItems
on rightKeySelector(right) equals leftKeySelector(left) into temp
from left in temp.DefaultIfEmpty()
select resultSelector(left, right);
return leftJoin.Union(rightJoin);
}
}
In the example, you would use it like this:
var test =
firstNames
.FullJoinDistinct(
lastNames,
f=> f.ID,
j=> j.ID,
(f,j)=> new {
ID = f == null ? j.ID : f.ID,
leftName = f == null ? null : f.Name,
rightName = j == null ? null : j.Name
}
);
In the future, as I learn more, I have a feeling I'll be migrating to @sehe's logic given it's popularity. But even then I'll have to be careful, because I feel it is important to have at least one overload that matches the syntax of the existing ".Join()" method if feasible, for two reasons:
I'm still new with generics, extensions, Func statements, and other features, so feedback is certainly welcome.
EDIT: Didn't take me long to realize there was a problem with my code. I was doing a .Dump() in LINQPad and looking at the return type. It was just IEnumerable, so I tried to match it. But when I actually did a .Where() or .Select() on my extension I got an error: "'System Collections.IEnumerable' does not contain a definition for 'Select' and ...". So in the end I was able to match the input syntax of .Join(), but not the return behavior.
EDIT: Added "TResult" to the return type for the function. Missed that when reading the Microsoft article, and of course it makes sense. With this fix, it now seems the return behavior is in line with my goals after all.
Ok, found it.
package.json must contain a dependency to angular-cli.
When I uninstalled my local angular-cli, npm also removed the dependency entry.
I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.
Viscon
you should be able to access them from $_POST
variable:
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val<br />\n";
}
I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():_x000D_
rolling = True; import random_x000D_
while rolling:_x000D_
roll = input("ENTER = roll; Q = quit ")_x000D_
if roll.lower() != 'q':_x000D_
num = (random.randint(1,6))_x000D_
print("----------------------"); print("you rolled " + str(num))_x000D_
else:_x000D_
rolling = False_x000D_
main()
_x000D_
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.
def find_substring():
s = 'bobobnnnnbobmmmbosssbob'
cnt = 0
for i in range(len(s)):
if s[i:i+3] == 'bob':
cnt += 1
print 'bob found: ' + str(cnt)
return cnt
def main():
print(find_substring())
main()
Here is representation of screen eclipse to make hierarachical.
+----------------------- | RESOURCE EXISTS ? (if private it is often checked AFTER auth check) +----------------------- | | NO | v YES v +----------------------- 404 | IS LOGGED-IN ? (authenticated, aka has session or JWT cookie) or +----------------------- 401 | | 403 NO | | YES 3xx v v 401 +----------------------- (404 no reveal) | CAN ACCESS RESOURCE ? (permission, authorized, ...) or +----------------------- redirect | | to login NO | | YES | | v v 403 OK 200, redirect, ... (or 404: no reveal) (or 404: resource does not exist if private) (or 3xx: redirection)
Checks are usually done in this order:
UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named 'unauthenticated' instead of 'unauthorized'. This can also happen after login if session expired. Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span. Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).
As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):
If you want to use SelectedValue then your combobox must be databound.
To set up the combobox:
ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
To get the data:
Function GetMailItems() As List(Of MailItem)
Dim mailItems = New List(Of MailItem)
Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
While Reader.Read()
mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
End While
End If
Return mailItems
End Function
Public Class MailItem
Public Sub New(ByVal id As Integer, ByVal name As String)
mID = id
mName = name
End Sub
Private mID As Integer
Public Property ID() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
End Class
So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.
I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.
In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))
In [18]: df1
Out[18]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A 10000 non-null values
dtypes: int64(1)
In [19]: df4 = pd.DataFrame()
The concat
In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop
This is equavalent of your append
In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of
3: 56.8 ms per loop
You don't have to add a layer for each border, just use a bezier path to draw them once.
CGRect rect = self.bounds;
CGPoint destPoint[4] = {CGPointZero,
(CGPoint){0, rect.size.height},
(CGPoint){rect.size.width, rect.size.height},
(CGPoint){rect.size.width, 0}};
BOOL position[4] = {_top, _left, _bottom, _right};
UIBezierPath *path = [UIBezierPath new];
[path moveToPoint:destPoint[3]];
for (int i = 0; i < 4; ++i) {
if (position[i]) {
[path addLineToPoint:destPoint[i]];
} else {
[path moveToPoint:destPoint[i]];
}
}
CAShapeLayer *borderLayer = [CAShapeLayer new];
borderLayer.frame = self.bounds;
borderLayer.path = path.CGPath;
borderLayer.lineWidth = _borderWidth ?: 1 / [UIScreen mainScreen].scale;
borderLayer.strokeColor = _borderColor.CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
[self.layer addSublayer:borderLayer];
Unless you are loading the files into memory each time you boot, use a database. Simple as that.
That is assuming that your colleges already have the program to handle queries to the files. If not, then use a database.
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
For Boot 2.0.0+ this works for me: server.servlet.context-path = /api
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
unsorted_list.sort(key=lambda x: x[3])
A quote from the documentation:
Using multiple commands and conditional processing symbols
You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.
For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful.
You can use the special characters listed in the following table to pass multiple commands.
& [...]
command1 & command2
Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.
&& [...]
command1 && command2
Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.
|| [...]
command1 || command2
Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).
( ) [...]
(command1 & command2)
Use to group or nest multiple commands.
; or ,
command1 parameter1;parameter2
Use to separate command parameters.
I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.
Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
Hope this Code you are looking for HTML:
<div class="showmore">
<div class="shorten_txt">
<h4> #@item.Title</h4>
<p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
</div>
</div>
SCRIPT:
var showChar = 100;
var ellipsestext = "[...]";
$('.showmore').each(function () {
$(this).find('.shorten_txt p').addClass('more_p').hide();
$(this).find('.shorten_txt p:first').removeClass('more_p').show();
$(this).find('.shorten_txt ul').addClass('more_p').hide();
//you can do this above with every other element
var teaser = $(this).find('.shorten_txt p:first').html();
var con_length = parseInt(teaser.length);
var c = teaser.substr(0, showChar);
var h = teaser.substr(showChar, con_length - showChar);
var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
'</span></span><span class="morecontent_txt">' + h
+ '</span>';
if (con_length > showChar) {
$(this).find(".shorten_txt p:first").html(html);
$(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
}
});
$(".showmore").click(function () {
if ($(this).hasClass("less")) {
$(this).removeClass("less");
} else {
$(this).addClass("less");
}
$(this).find('.shorten_txt p:first span.moreelipses').toggle();
$(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
$(this).find('.shorten_txt .more_p').toggle();
return false;
});
After the post from Gabor Grothendieck post at the r-help mailing list
years<-c("20 years old", "1 years old")
library(gsubfn)
pat <- "[-+.e0-9]*\\d"
sapply(years, function(x) strapply(x, pat, as.numeric)[[1]])
You can also check for socket output stream error while writing to client socket.
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
USE information_schema;
SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE (table_name = *tablename*) AND NOT (REFERENCED_TABLE_NAME IS NULL)
Your define following in router.js
$stateProvider.state('users', {
url: '/users',
controller: 'UsersCtrl',
params: {
obj: null
}
})
Your controller need add $stateParams.
function UserCtrl($stateParams) {
console.log($stateParams);
}
You can send an object by parameter as follows.
$state.go('users', {obj:yourObj});
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
(Firstly read the other answers which has explained the for
in the <label></label>
tags.
Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1"
but with different ids id="r1_1" ... id="r1_2"
So this way the answer is more clear and removes the conflicts between name and ids as well.
You need different ids for different options of the radio box.
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
<label for="r1_1">button text one</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
<label for="r1_2">button text two</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
<label for="r1_3">button text three</label>
_x000D_
A Dictionary is a Hash Table, so you have no idea the order of insertion!
If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.
E.g.:
public MyDictionary<K, T> : IDictionary<K, T>
{
private IDictionary<K, T> _InnerDictionary;
public K LastInsertedKey { get; set; }
public MyDictionary()
{
_InnerDictionary = new Dictionary<K, T>();
}
#region Implementation of IDictionary
public void Add(KeyValuePair<K, T> item)
{
_InnerDictionary.Add(item);
LastInsertedKey = item.Key;
}
public void Add(K key, T value)
{
_InnerDictionary.Add(key, value);
LastInsertedKey = key;
}
.... rest of IDictionary methods
#endregion
}
You will run into problems however when you use .Remove()
so to overcome this you will have to keep an ordered list of the keys inserted.
Just use std::string
:
std::cout << std::string( n, ' ' );
In many cases, however, depending on what comes next, is may be
simpler to just add n
to the parameter to an std::setw
.
I wrote a tree library that plays nicely with Java8 and that has no other dependencies. It also provides a loose interpretation of some ideas from functional programming and lets you map/filter/prune/search the entire tree or subtrees.
https://github.com/RutledgePaulV/prune
The implementation doesn't do anything special with indexing and I didn't stray away from recursion, so it's possible that with large trees performance will degrade and you could blow the stack. But if all you need is a straightforward tree of small to moderate depth, I think it works well enough. It provides a sane (value based) definition of equality and it also has a toString implementation that lets you visualize the tree!
In case if you get this exception in SpringBoot
application even though the entities are annotated with Entity
annotation, it might be due to the spring not aware of where to scan for entities
To explicitly specify the package, add below
@SpringBootApplication
@EntityScan({"model.package.name"})
public class SpringBootApp {...}
note: If you model classes resides in the same or sub packages of SpringBootApplication
annotated class, no need to explicitly declare the EntityScan
, by default it will scan
Yes. std::exception
is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent document on good style for exceptions and error handling. It's worth a read.
Try this :
width:auto;
margin-right:50px;
Add the MessageUI.Framework and use the following code
#import <MessageUI/MessageUI.h>
And then:
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *messageComposer =
[[MFMessageComposeViewController alloc] init];
NSString *message = @"Your Message here";
[messageComposer setBody:message];
messageComposer.messageComposeDelegate = self;
[self presentViewController:messageComposer animated:YES completion:nil];
}
and the delegate method -
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result {
[self dismissViewControllerAnimated:YES completion:nil];
}
Apache Commons Lang has StringUtils.isEmpty(String str)
method which returns true if argument is empty or null
This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.
$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);
var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);
Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.
But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.
$password = Input::get('password_from_user');
$hashed = Hash::make($password); // save $hashed value
// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
// Password is not matching
} else {
// Password is matching
}
In addition to Delan Azabani's answer, I like to share my console.js
, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log
function, but no console.debug
:
// Create a noop console object if the browser doesn't provide one...
if (!window.console){
window.console = {};
}
// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
if (!window.console.debug && typeof window.console.log !== 'undefined') {
window.console.debug = window.console.log;
}
}
// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
for (var i = 0; i < names.length; ++i){
if(!window.console[names[i]]){
window.console[names[i]] = function() {};
}
}
I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.
@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL
This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.
I got it!
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");
$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime= $vidTime['contentDetails']['duration'];
}
There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId
that I had gotten off of the returned list of the videos from the channel I am showing the videos from...
It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.
Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
You could open the file up and use StreamReader.ReadLine to read the file in line-by-line. Then you can use String.Split to break each line into pieces (use a \t delimiter) to extract the second number.
As the number of items is different you would need to search the string for the pattern 'item\*.ddj'.
To delete an item you could (for example) keep all of the file's contents in memory and write out a new file when the user clicks 'Save'.
Actually, a decent shortcut method for getting the colors to cycle is to use hold all;
in place of hold on;
. Each successive plot
will rotate (automatically for you) through MATLAB's default colormap.
From the MATLAB site on hold
:
hold all
holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.
Perl is a context-based language. It doesn't do its work according to the data you give it. Instead, it figures out how to treat the data based on the operators you use and the context in which you use them. If you do numbers sorts of things, you get numbers:
# numeric addition with strings:
my $sum = '5.45' + '0.01'; # 5.46
If you do strings sorts of things, you get strings:
# string replication with numbers:
my $string = ( 45/2 ) x 4; # "22.522.522.522.5"
Perl mostly figures out what to do and it's mostly right. Another way of saying the same thing is that Perl cares more about the verbs than it does the nouns.
Are you trying to do something and it isn't working?
In case you were looking to transform your column number into a letter:
Function ConvertToLetter(iCol As Integer) As String
Dim iAlpha As Integer
Dim iRemainder As Integer
iAlpha = Int(iCol / 27)
iRemainder = iCol - (iAlpha * 26)
If iAlpha > 0 Then
ConvertToLetter = Chr(iAlpha + 64)
End If
If iRemainder > 0 Then
ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
End If
End Function
This way you could do something like this:
Function selectColumnRange(colNum As Integer, targetWorksheet As Worksheet)
Dim colLetter As String
Dim testRange As Range
colLetter = ConvertToLetter(colNum)
testRange = targetWorksheet.Range(colLetter & ":" & colLetter).Select
End Function
That example function would select the entire column ( i.e. Range("A:A").Select)
I just don't see the functional and seamless reason for nulls not to be comparable to other values or other nulls, cause we can clearly compare it and say they are the same or not in our context. It's funny. Just because of some logical conclusions and consistency we need to bother constantly with it. It's not functional, make it more functional and leave it to philosophers and scientists to conclude if it's consistent or not and does it hold "universal logic". :) Someone may say that it's because of indexes or something else, I doubt that those things couldn't be made to support nulls same as values. It's same as comparing two empty glasses, one is vine glass and other is beer glass, we are not comparing the types of objects but values they contain, same as you could compare int and varchar, with null it's even easier, it's nothing and what two nothingness have in common, they are the same, clearly comparable by me and by everyone else that write sql, because we are constantly breaking that logic by comparing them in weird ways because of some ANSI standards. Why not use computer power to do it for us and I doubt it would slow things down if everything related is constructed with that in mind. "It's not null it's nothing", it's not apple it's apfel, come on... Functionally is your friend and there is also logic here. In the end only thing that matter is functionality and does using nulls in that way brings more or less functionality and ease of use. Is it more useful?
Consider this code:
SELECT CASE WHEN NOT (1 = null or (1 is null and null is null)) THEN 1 ELSE 0 end
How many of you knows what will this code return? With or without NOT it returns 0. To me that is not functional and it's confusing. In c# it's all as it should be, comparison operations return value, logically this too produces value, because if it didn't there is nothing to compare (except. nothing :) ). They just "said": anything compared to null "returns" 0 and that creates many workarounds and headaches.
This is the code that brought me here:
where a != b OR (a is null and b IS not null) OR (a IS not null and b IS null)
I just need to compare if two fields (in where) have different values, I could use function, but...
To learn what row was selected, add a ListSelectionListener
, as shown in How to Use Tables in the example SimpleTableSelectionDemo
. A JList
can be constructed directly from the linked list's toArray()
method, and you can add a suitable listener to it for details.
You can find blocking sql and wait sql by running this:
SELECT
t1.resource_type ,
DB_NAME( resource_database_id) AS dat_name ,
t1.resource_associated_entity_id,
t1.request_mode,
t1.request_session_id,
t2.wait_duration_ms,
( SELECT TEXT FROM sys.dm_exec_requests r CROSS apply sys.dm_exec_sql_text ( r.sql_handle ) WHERE r.session_id = t1.request_session_id ) AS wait_sql,
t2.blocking_session_id,
( SELECT TEXT FROM sys.sysprocesses p CROSS apply sys.dm_exec_sql_text ( p.sql_handle ) WHERE p.spid = t2.blocking_session_id ) AS blocking_sql
FROM
sys.dm_tran_locks t1,
sys.dm_os_waiting_tasks t2
WHERE
t1.lock_owner_address = t2.resource_address
Here we go... just copy the code to a module, it's ready to use
Private Type hashtable
key As Variant
value As Variant
End Type
Private GetErrMsg As String
Private Function CreateHashTable(htable() As hashtable) As Boolean
GetErrMsg = ""
On Error GoTo CreateErr
ReDim htable(0)
CreateHashTable = True
Exit Function
CreateErr:
CreateHashTable = False
GetErrMsg = Err.Description
End Function
Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
GetErrMsg = ""
On Error GoTo AddErr
Dim idx As Long
idx = UBound(htable) + 1
Dim htVal As hashtable
htVal.key = key
htVal.value = value
Dim i As Long
For i = 1 To UBound(htable)
If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
Next i
ReDim Preserve htable(idx)
htable(idx) = htVal
AddValue = idx
Exit Function
AddErr:
AddValue = 0
GetErrMsg = Err.Description
End Function
Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
GetErrMsg = ""
On Error GoTo RemoveErr
Dim i As Long, idx As Long
Dim htTemp() As hashtable
idx = 0
For i = 1 To UBound(htable)
If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
ReDim Preserve htTemp(idx)
AddValue htTemp, htable(i).key, htable(i).value
idx = idx + 1
End If
Next i
If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"
htable = htTemp
RemoveValue = True
Exit Function
RemoveErr:
RemoveValue = False
GetErrMsg = Err.Description
End Function
Private Function GetValue(htable() As hashtable, key As Variant) As Variant
GetErrMsg = ""
On Error GoTo GetValueErr
Dim found As Boolean
found = False
For i = 1 To UBound(htable)
If htable(i).key = key And IsEmpty(htable(i).key) = False Then
GetValue = htable(i).value
Exit Function
End If
Next i
Err.Raise 9997, , "Key [" & CStr(key) & "] not found"
Exit Function
GetValueErr:
GetValue = ""
GetErrMsg = Err.Description
End Function
Private Function GetValueCount(htable() As hashtable) As Long
GetErrMsg = ""
On Error GoTo GetValueCountErr
GetValueCount = UBound(htable)
Exit Function
GetValueCountErr:
GetValueCount = 0
GetErrMsg = Err.Description
End Function
To use in your VB(A) App:
Public Sub Test()
Dim hashtbl() As hashtable
Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
Debug.Print ""
Debug.Print "ID Test Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
Debug.Print ""
Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
Debug.Print ""
Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
Debug.Print ""
Debug.Print "Hashtable Content:"
For i = 1 To UBound(hashtbl)
Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
Next i
Debug.Print ""
Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub
Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.
I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4
node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.
UPDATE - for an example of this working, I used this technique in the Carota editor.
Following on from ellisbben's answer, here is an enhanced version to get the ascent and descent from the baseline, i.e. same as tmAscent
and tmDescent
returned by Win32's GetTextMetric API. This is needed if you want to do a word-wrapped run of text with spans in different fonts/sizes.
The above image was generated on a canvas in Safari, red being the top line where the canvas was told to draw the text, green being the baseline and blue being the bottom (so red to blue is the full height).
Using jQuery for succinctness:
var getTextHeight = function(font) {
var text = $('<span>Hg</span>').css({ fontFamily: font });
var block = $('<div style="display: inline-block; width: 1px; height: 0px;"></div>');
var div = $('<div></div>');
div.append(text, block);
var body = $('body');
body.append(div);
try {
var result = {};
block.css({ verticalAlign: 'baseline' });
result.ascent = block.offset().top - text.offset().top;
block.css({ verticalAlign: 'bottom' });
result.height = block.offset().top - text.offset().top;
result.descent = result.height - result.ascent;
} finally {
div.remove();
}
return result;
};
In addition to a text element, I add a div with display: inline-block
so I can set its vertical-align
style, and then find out where the browser has put it.
So you get back an object with ascent
, descent
and height
(which is just ascent
+ descent
for convenience). To test it, it's worth having a function that draws a horizontal line:
var testLine = function(ctx, x, y, len, style) {
ctx.strokeStyle = style;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + len, y);
ctx.closePath();
ctx.stroke();
};
Then you can see how the text is positioned on the canvas relative to the top, baseline and bottom:
var font = '36pt Times';
var message = 'Big Text';
ctx.fillStyle = 'black';
ctx.textAlign = 'left';
ctx.textBaseline = 'top'; // important!
ctx.font = font;
ctx.fillText(message, x, y);
// Canvas can tell us the width
var w = ctx.measureText(message).width;
// New function gets the other info we need
var h = getTextHeight(font);
testLine(ctx, x, y, w, 'red');
testLine(ctx, x, y + h.ascent, w, 'green');
testLine(ctx, x, y + h.height, w, 'blue');
If you need two variables in the XML
, you can use:
%1$d text... %2$d
or %1$s text... %2$s
for string variables.
Example :
<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>
String site = "site.tld";
String days = "11";
//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();
For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:
function Header() {
return (
<div>
<img src="images/logo.jpg" alt="logo"/>
</div>
);
}
Yes, no need to use /public/ in the source.
Read further: https://daveceddia.com/react-image-tag/.
Welcome to 2017 these days will using vW
and vH
do the trick
html, body {_x000D_
margin: 0; padding: 0;_x000D_
width: 100%; height: 100%;_x000D_
}_x000D_
_x000D_
ul {_x000D_
background: #CCC;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
list-style-position: outside;_x000D_
margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
li {_x000D_
width: 100%;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 100%;_x000D_
height: 410px;_x000D_
}_x000D_
_x000D_
.outer-wrapper {_x000D_
position: absolute;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
top: 0;_x000D_
margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
.inner-wrapper {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
width: 100vw; /* only change is here "%" to "vw" ! */_x000D_
height: 100vh; /* only change is here "%" to "vh" ! */_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
<img src="#">_x000D_
<div class="outer-wrapper">_x000D_
<div class="inner-wrapper">_x000D_
<h1>My Title</h1>_x000D_
<h5>Subtitle</h5>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
</ul>
_x000D_
adb shell
am start -n com.package.name/com.package.name.ActivityName
Or you can use this directly:
adb shell am start -n com.package.name/com.package.name.ActivityName
You can also specify actions to be filter by your intent-filters:
am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName
The git describe
command creates a slightly more human readable name that refers to a specific commit. For example, from the documentation:
With something like git.git current tree, I get:
[torvalds@g5 git]$ git describe parent v1.0.4-14-g2414721
i.e. the current head of my "parent" branch is based on v1.0.4, but since it has a few commits on top of that, describe has added the number of additional commits ("14") and an abbreviated object name for the commit itself ("2414721") at the end.
As long as you use sensibly named tags to tag particular releases, this can be considered to be roughly equivalent to a SVN "revision number".
Whenever there are issues of mismatched axis limits, the right tool in base
graphics is to use matplot
. The key is to leverage the from
and to
arguments to density.default
. It's a bit hackish, but fairly straightforward to roll yourself:
set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)
xrng = range(x1, x2)
#force the x values at which density is
# evaluated to be the same between 'density'
# calls by specifying 'from' and 'to'
# (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])
matplot(kde1$x, cbind(kde1$y, kde2$y))
Add bells and whistles as desired (matplot
accepts all the standard plot
/par
arguments, e.g. lty
, type
, col
, lwd
, ...).
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
This is caused by having JAVA JRE installed as opposed to JAVA JDK.
The solution is simple:
sudo apt-get install openjdk-7-jdk
http://www.maxmakedesign.co.uk/development/2013/android-studio-tools-jar-classpath/
The rule is as following :
A B
B as a descendant of A
A > B
B as a child of A
So
div.dropdown *
and not
div.dropdown > *
TROUBLESHOOTING STEPS (Doc ID 730066.1)
Connection Timeout errors ORA-3135 and ORA-3136 A connection timeout error can be issued when an attempt to connect to the database does not complete its connection and authentication phases within the time period allowed by the following: SQLNET.INBOUND_CONNECT_TIMEOUT and/or INBOUND_CONNECT_TIMEOUT_ server-side parameters.
Starting with Oracle 10.2, the default for these parameters is 60 seconds where in previous releases it was 0, meaning no timeout.
On a timeout, the client program will receive the ORA-3135 (or possibly TNS-3135) error:
ORA-3135 connection lost contact
and the database will log the ORA-3136 error in its alert.log:
... Sat May 10 02:21:38 2008 WARNING: inbound connection timed out (ORA-3136) ...
When a database session is in the authentication phase, it will issue a sequence of SQL statements. The authentication is not complete until all these are parsed, executed, fetched completely. Some of the SQL statements in this list e.g. on 10.2 are:
select value$ from props$ where name = 'GLOBAL_DB_NAME'
select privilege#,level from sysauth$ connect by grantee#=prior privilege#
and privilege#>0 start with grantee#=:1 and privilege#>0
select SYS_CONTEXT('USERENV', 'SERVER_HOST'), SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME'),
SYS_CONTEXT('USERENV', 'INSTANCE_NAME'), SYS_CONTEXT('USERENV', 'SERVICE_NAME'),
INSTANCE_NUMBER, STARTUP_TIME, SYS_CONTEXT('USERENV', 'DB_DOMAIN')
from v$instance where INSTANCE_NAME=SYS_CONTEXT('USERENV', 'INSTANCE_NAME')
select privilege# from sysauth$ where (grantee#=:1 or grantee#=1) and privilege#>0
ALTER SESSION SET NLS_LANGUAGE= 'AMERICAN' NLS_TERRITORY= 'AMERICA' NLS_CURRENCY= '$'
NLS_ISO_CURRENCY= 'AMERICA' NLS_NUMERIC_CHARACTERS= '.,' NLS_CALENDAR= 'GREGORIAN'
NLS_DATE_FORMAT= 'DD-MON-RR' NLS_DATE_LANGUAGE= 'AMERICAN' NLS_SORT= 'BINARY' TIME_ZONE= '+02:00'
NLS_COMP= 'BINARY' NLS_DUAL_CURRENCY= '$' NLS_TIME_FORMAT= 'HH.MI.SSXFF AM' NLS_TIMESTAMP_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM' NLS_TIME_TZ_FORMAT= 'HH.MI.SSXFF AM TZR' NLS_TIMESTAMP_TZ_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM TZR'
NOTE: The list of SQL above is not complete and does not represent the ordering of the authentication SQL . Differences may also exist from release to release.
The above SQL statements need to be Parsed, Executed and Fetched as happens for all SQL inside an Oracle Database. It follows that any problem encountered during these phases which appears as a hang or severe slow performance may result in a timeout.
Symptoms of such hangs will be seen by the authenticating session as waits for: • cursor: pin S wait on X • latch: row cache objects • row cache lock Other types of wait events are possible; this list may not be complete.
The issue here is that the authenticating session is blocked waiting to get a shared resource which is held by another session inside the database. That blocker session is itself occupied in a long-running activity (or its own hang) which prevents it from releasing the shared resource needed by the authenticating session in a timely fashion. This results in the timeout being eventually reported to the authenticating session.
In such situations, we need to find out the blocker process holding the shared resource needed by the authenticating session in order to see what is happening to it.
Typical diagnostics used in such cases are the following:
$ sqlplus -prelim '/ as sysdba' oradebug setmypid oradebug unlimit oradebug dump systemstate 266 ...wait 90 seconds oradebug dump systemstate 266 ...wait 90 seconds oradebug dump systemstate 266 quit
Examples of issues which can result in Authentication hangs
Unpublished Bug 7039896 workaround parameter _enable_shared_pool_durations=false see Note 7039896.8
Other approaches to avoid the problem
In some cases, it may be possible to avoid problems with Authentication SQL by pinning such statements in the Shared Pool soon after the instance is started and they are freshly loaded. You can use the following artcile to advise on this: Document 726780.1 How to Pin a Cursor in the Shared Pool using DBMS_SHARED_POOL.KEEP
Pinning will prevent them from being flushed out due to inactivity and aging and will therefore prevent them for needing to be reloaded in the future i.e. needing to be reparsed and becoming susceptible to Authentication hang issues.
That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:
public class GenericList <T> extends ArrayList<T>
{
private Class<T> genericType;
public GenericList(Class<T> c)
{
this.genericType = c;
}
public Class<T> getGenericType()
{
return genericType;
}
}
You can examine the url through several Request
fields:
Imagine your application is listening on the following application root:
http://www.example.com/myapplication
And a user requests the following URI:
http://www.example.com/myapplication/foo/page.html?x=y
In this case the values of the above mentioned attributes would be the following:
path /foo/page.html full_path /foo/page.html?x=y script_root /myapplication base_url http://www.example.com/myapplication/foo/page.html url http://www.example.com/myapplication/foo/page.html?x=y url_root http://www.example.com/myapplication/
You can easily extract the host part with the appropriate splits.
I have Wondows 7 64 bit (MacBook Pro), installed both Java JDK x86 and x64 with JAVA_HOME
pointing at x32 during installation of Android SDK, later after installation JAVA_HOME
pointing at x64.
My problem was that Android SDK manager didn't launch, cmd window just flashes for a second and that's it. Like many others looked around and tried many suggestions with no juice!
My solution was in adding bin the JAVA_HOME
path:
C:\Program Files\Java\jdk1.7.0_09\bin
instead of what I entered for the start:
C:\Program Files\Java\jdk1.7.0_09
Hope this helps others.... good luck!
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
I created a jQuery version of PhpMyCoder's answer:
$('form').submit(function( e ) {
if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
//Prevent default and display error
alert("File is wrong type or over 10Mb in size!");
e.preventDefault();
}
});
function get_extension(filename) {
return filename.split('.').pop().toLowerCase();
}
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
To view Theme files for ST3, install PackageResourceViewer via PackageControl.
Then, you can use the Ctrl + Shift + P >> PackageResourceViewer: Open Resource
to view theme files.
To edit a specific background color, you need to create a new file in your user packages folder Packages/User/SublimeLinter
with the same name as the theme currently applied to your sublime text file.
However, if your theme is a 3rd party theme package installed via package control, you can edit the hex value in that file directly, under background. For example:
<dict>
<dict>
<key>background</key>
<string>#073642</string>
</dict>
</dict>
Otherwise, if you are trying to modify a native sublime theme, add the following to the new file you create (named the same as the native theme, such as Monokai.sublime-color-scheme
) with your color choice
{
"globals":
{
"background": "rgb(5,5,5)"
}
}
Then, you can open the file you wish the syntax / color to be applied to and then go to Syntax-Specific settings (under Preferences) and add the path of the file to the syntax specific settings file like so:
{
"color_scheme": "Packages/User/SublimeLinter/Monokai.sublime-color-scheme"
}
Note that if you have installed a theme via package control, it probably has the .tmTheme
file extension.
If you are wanting to edit the background color of the sidebar to be darker, go to Preferences > Theme > Adaptive.sublime-theme
This my answer based on my personal experience and info gleaned from the accepted answer on this page, if you'd like more information.
Some notes that I also found useful:
Keep your default values on the right side.
function whatever($var1, $var2, $var3="constant", $var4="another")
The default value of the argument must be a constant expression. It can't be a variable or a function call.
On Debian, using openjdk version "1.8.0_212", I found cacerts here:
/etc/ssl/certs/java/cacerts
Sure would be handy if there was a standard command that would print out this path.
Try this it may help you:
private void changeFragment(Fragment targetFragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
Check out Marker Clusterer for V3 - this library clusters nearby points into a group marker. The map zooms in when the clusters are clicked. I'd imagine when zoomed right in you'd still have the same problem with markers on the same spot though.
Following command worked out for me nicely. It gives you the OS name and version.
lsb_release -a
If you have FTP access to your account:
First, login to your wp-admin and go to Settings > Permalinks
You should see something at the bottom that says:
"If your .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all."
If this is true do the following:
Go into preferences for your FTP client and make sure hidden files are displayed (varies depending on your FTP client) - If you don't do this you won't be able to find your htaccess file
Go to the folder that your wp-admin, wp-content, wp-includes directories are located. Check for .htaccess file. If it exists skip to step 4
If it does not exist, create a new blank file in your FTP program called .htaccess
Change the CHMOD for your .htaccess file to 666 (your preference on how you want to do this)
Go back to your Permalinks page and edit the link structure you want. Problem should be solved!
Make sure to change the chmod of the htaccess file back to 644 after you are done.
Just had the same problem and it seemed to fix it instantly! Good luck!
Due to the locking implementation issues, MySQL
does not allow referencing the affected table with DELETE
or UPDATE
.
You need to make a JOIN
here instead:
DELETE gc.*
FROM guide_category AS gc
LEFT JOIN
guide AS g
ON g.id_guide = gc.id_guide
WHERE g.title IS NULL
or just use a NOT IN
:
DELETE
FROM guide_category AS gc
WHERE id_guide NOT IN
(
SELECT id_guide
FROM guide
)
1 + 2 + 4 conditions: starts|ends, but not in the middle
/^@[^@]*@?$|^@?[^@]*@$/
is almost the same that:
/^@?[^@]*@?$/
but this one matches any string without @, sample 'my name is hal9000'
My first suggestion would be use your calendar table, if you don't have one, then create one. They are very useful. Your query is then as simple as:
DECLARE @MinDate DATE = '20140101',
@MaxDate DATE = '20140106';
SELECT Date
FROM dbo.Calendar
WHERE Date >= @MinDate
AND Date < @MaxDate;
If you don't want to, or can't create a calendar table you can still do this on the fly without a recursive CTE:
DECLARE @MinDate DATE = '20140101',
@MaxDate DATE = '20140106';
SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b;
For further reading on this see:
With regard to then using this sequence of dates in a cursor, I would really recommend you find another way. There is usually a set based alternative that will perform much better.
So with your data:
date | it_cd | qty
24-04-14 | i-1 | 10
26-04-14 | i-1 | 20
To get the quantity on 28-04-2014 (which I gather is your requirement), you don't actually need any of the above, you can simply use:
SELECT TOP 1 date, it_cd, qty
FROM T
WHERE it_cd = 'i-1'
AND Date <= '20140428'
ORDER BY Date DESC;
If you don't want it for a particular item:
SELECT date, it_cd, qty
FROM ( SELECT date,
it_cd,
qty,
RowNumber = ROW_NUMBER() OVER(PARTITION BY ic_id
ORDER BY date DESC)
FROM T
WHERE Date <= '20140428'
) T
WHERE RowNumber = 1;
Add below lib inside gradle file
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
Create class HomeActivityTest inside androidTest directory and before running the test add flurry_api_key and sender_id string inside string resource file and change the value for failure and success case.
@RunWith(AndroidJUnit4.class)
public class HomeActivityTest
{
private static final String SENDER_ID = "abc";
private static final String RELEASE_FLURRY_API_KEY = "xyz";
@Test
public void gcmRegistrationId_isCorrect() throws Exception
{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
Assert.assertEquals(SENDER_ID, appContext.getString(R.string.sender_id));
}
@Test
public void flurryApiKey_isCorrect() throws Exception
{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
Assert.assertEquals(RELEASE_FLURRY_API_KEY, appContext.getString(R.string.flurry_api_key));
}
}
It depends on various things. But in general algorithms using a Divide-and-Conquer / dichotomic approach will perform well for sorting problems as they present interesting average-case complexities.
To understand which algorithms work best, you will need basic knowledge of algorithms complexity and big-O notation, so you can understand how they rate in terms of average case, best case and worst case scenarios. If required, you'd also have to pay attention to the sorting algorithm's stability.
For instance, usually an efficient algorithm is quicksort. However, if you give quicksort a perfectly inverted list, then it will perform poorly (a simple selection sort will perform better in that case!). Shell-sort would also usually be a good complement to quicksort if you perform a pre-analysis of your list.
Have a look at the following, for "advanced searches" using divide and conquer approaches:
And these more straighforward algorithms for less complex ones:
The above are the usual suspects when getting started, but there are countless others.
As pointed out by R. in the comments and by kriss in his answer, you may want to have a look at HeapSort, which provides a theoretically better sorting complexity than a quicksort (but will won't often fare better in practical settings). There are also variants and hybrid algorithms (e.g. TimSort).