If you're using fragments hosted on an activity you can do something like this:
public abstract class BaseFragment extends Fragment {
private boolean mSaveView = false;
private SoftReference<View> mViewReference;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mSaveView) {
if (mViewReference != null) {
final View savedView = mViewReference.get();
if (savedView != null) {
if (savedView.getParent() != null) {
((ViewGroup) savedView.getParent()).removeView(savedView);
return savedView;
}
}
}
}
final View view = inflater.inflate(getFragmentResource(), container, false);
mViewReference = new SoftReference<View>(view);
return view;
}
protected void setSaveView(boolean value) {
mSaveView = value;
}
}
public class MyFragment extends BaseFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setSaveView(true);
final View view = super.onCreateView(inflater, container, savedInstanceState);
ListView placesList = (ListView) view.findViewById(R.id.places_list);
if (placesList.getAdapter() == null) {
placesList.setAdapter(createAdapter());
}
}
}
I found that Glassfish by default is looking at [Glassfish install location]\glassfish\domains[your domain]\ as the default working directory... you can drop the log4j.properties file in this location and initialize it in your code using PropertyConfigurator as previously mentioned...
Properties props = System.getProperties();
System.out.println("Current working directory is " + props.getProperty("user.dir"));
PropertyConfigurator.configure("log4j.properties");
Why not just return the worksheet name with address = cell.Worksheet.Name then you can concatenate the address back on like this address = cell.Worksheet.Name & "!" & cell.Address
One of the comments mentioned using the GitHub GUI, but it didn't give any specific help on using and notice that most if not all the answers were useful at the command prompt only.
If you want to use the GitHub GUI, you can follow these steps:
After a moment with a spinning GitHub icon, your source code will belong to a local repository and pushed/synchronised with a remote repository on your GitHub account. All of this is presuming you've previously set up the GitHub GUI, your GitHub account, and SSH keys.
If you're interested in the output, you can use this function:
private static string ExecCommand(string filename, string arguments)
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(filename);
psi.Arguments = arguments;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
process.StartInfo = psi;
StringBuilder output = new StringBuilder();
process.OutputDataReceived += (sender, e) => { output.AppendLine(e.Data); };
process.ErrorDataReceived += (sender, e) => { output.AppendLine(e.Data); };
// run the process
process.Start();
// start reading output to events
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// wait for process to exit
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception("Command " + psi.FileName + " returned exit code " + process.ExitCode);
return output.ToString();
}
It runs the given command line program, waits for it to finish and returns the output as string.
md5.h
also have MD5_*
functions very useful for big file
#include <openssl/md5.h>
#include <fstream>
.......
std::ifstream file(filename, std::ifstream::binary);
MD5_CTX md5Context;
MD5_Init(&md5Context);
char buf[1024 * 16];
while (file.good()) {
file.read(buf, sizeof(buf));
MD5_Update(&md5Context, buf, file.gcount());
}
unsigned char result[MD5_DIGEST_LENGTH];
MD5_Final(result, &md5Context);
Very simple, isn`t it? Convertion to string also very simple:
#include <sstream>
#include <iomanip>
.......
std::stringstream md5string;
md5string << std::hex << std::uppercase << std::setfill('0');
for (const auto &byte: result)
md5string << std::setw(2) << (int)byte;
return md5string.str();
My preferred solution for this would be to do the resizing server-side, so you are transmitting less unnecessary data.
If you have to do it client-side though, and need to keep the image ratio, you could use the below:
var image_from_ajax = new Image();
image_from_ajax.src = fetch_image_from_ajax(); // Downloaded via ajax call?
image_from_ajax = rescaleImage(image_from_ajax);
// Rescale the given image to a max of max_height and max_width
function rescaleImage(image_name)
{
var max_height = 100;
var max_width = 100;
var height = image_name.height;
var width = image_name.width;
var ratio = height/width;
// If height or width are too large, they need to be scaled down
// Multiply height and width by the same value to keep ratio constant
if(height > max_height)
{
ratio = max_height / height;
height = height * ratio;
width = width * ratio;
}
if(width > max_width)
{
ratio = max_width / width;
height = height * ratio;
width = width * ratio;
}
image_name.width = width;
image_name.height = height;
return image_name;
}
Optional Chaining operator can also be used for this
?.
sorce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
Swift 3/4/5 Solution
Select Row
let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
myTableView.delegate?.tableView!(myTableView, didSelectRowAt: indexPath)
DeSelect Row
let deselectIndexPath = IndexPath(row: 7, section: 0)
tblView.deselectRow(at: deselectIndexPath, animated: true)
tblView.delegate?.tableView!(tblView, didDeselectRowAt: indexPath)
The best way is to use Array#to_h
:
[ [:apple,1],[:banana,2] ].to_h #=> {apple: 1, banana: 2}
Note that to_h
also accepts a block:
[:apple, :banana].to_h { |fruit| [fruit, "I like #{fruit}s"] }
# => {apple: "I like apples", banana: "I like bananas"}
Note: to_h
accepts a block in Ruby 2.6.0+; for early rubies you can use my backports
gem and require 'backports/2.6.0/enumerable/to_h'
to_h
without a block was introduced in Ruby 2.1.0.
Before Ruby 2.1, one could use the less legible Hash[]
:
array = [ [:apple,1],[:banana,2] ]
Hash[ array ] #= > {:apple => 1, :banana => 2}
Finally, be wary of any solutions using flatten
, this could create problems with values that are arrays themselves.
I removed the bin and obj folders from old C# projects using git on windows. Be careful with
git filter-branch --tree-filter "rm -rf bin" --prune-empty HEAD
It destroys the integrity of the git installation by deleting the usr/bin folder in the git install folder.
Cannot comment anymore but voted it up and wanted to let folks know that "
works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src="(.*)".*"
using the escaped version instead of double-quotes.
To define this on a permanent basis for the current user, create (or edit) the .vimrc
file:
$ vim ~/.vimrc
Then, paste the configuration below into the file. Once vim is restarted, the tab settings will apply.
set tabstop=4 " The width of a TAB is set to 4.
" Still it is a \t. It is just that
" Vim will interpret it to be having
" a width of 4.
set shiftwidth=4 " Indents will have a width of 4
set softtabstop=4 " Sets the number of columns for a TAB
set expandtab " Expand TABs to spaces
If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.
Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.
Above description is taken from MYSQL official website.
The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
or
http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html
Maybe you are asking for:
Character.toChars(65) // returns ['A']
More info: Character.toChars(int codePoint)
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here's the history and the fix:
pip uninstall opencv-python # -- the original step. failed.
ImportError: DLL load failed: The specified module could not be found.
I did this into my python3.6 environment and got this error.
python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.
Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.
finally, this fixed it:
pip uninstall opencv-python
(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.
>>>import cv2
>>>
working!
For Symfony3 In your controller try
$request->server->get('DOCUMENT_ROOT').$request->getBasePath()
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName
could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook
could be the correct choice, if it is guaranteed to be active at execution time.)
If you never plan to interact with the repository from which you cloned, you can do a full git clone and rewrite your repository using git filter-branch --subdirectory-filter. This way, at least the history will be preserved.
The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
You could print the backspace character \b
as many times as the characters which were printed before.
System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");
Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console?
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
XJones' answer worked like charm.
But he didn't mentioned/declared variables _params
, BoundaryConstant
and requestURL
. So, i thought of posting that part as an add-on to his post, so that it may help others in future.
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = [NSString stringWithString:@"file"];
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""];
As i mentioned earler, this is not an answer by itself, just an addon to XJones' post.
No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.
You may need this way X Macros
Untested. Modify to suit:
$form = $('#my-form');
$rows = $form.find('.person-input-row');
$('button#add-new').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
This is better than copying innerHTML because you will lose all attached events etc.
[revision 2012, no inline handler, preserve textarea enter handling]
function checkEnter(e){
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">
document.querySelector('form').onkeypress = checkEnter;
For me the solution was besides using "Ntlm" as credential type:
XxxSoapClient xxxClient = new XxxSoapClient();
ApplyCredentials(userName, password, xxxClient.ClientCredentials);
private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
{
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
clientCredentials.Windows.ClientCredential.UserName = userName;
clientCredentials.Windows.ClientCredential.Password = password;
clientCredentials.Windows.AllowNtlm = true;
clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
}
If you're behind a corporate proxy, try this setting for npm with your company's proxy:
npm --https-proxy=http://proxy.company.com install express -g
In Swift:
func pathForResource( name: String?,
ofType ext: String?,
inDirectory subpath: String?) -> String? {
// **name:** Name of Hmtl
// **ofType ext:** extension for type of file. In this case "html"
// **inDirectory subpath:** the folder where are the file.
// In this case the file is in root folder
let path = NSBundle.mainBundle().pathForResource( "dados",
ofType: "html",
inDirectory: "root")
var requestURL = NSURL(string:path!)
var request = NSURLRequest(URL:requestURL)
webView.loadRequest(request)
}
I use something like this to load properties file.
final ResourceBundle bundle = ResourceBundle
.getBundle("properties/errormessages");
for (final Enumeration<String> keys = bundle.getKeys(); keys
.hasMoreElements();) {
final String key = keys.nextElement();
final String value = bundle.getString(key);
prop.put(key, value);
}
Problem behind the error: If you are trying to access Oracle database you will not able to access inserted data until the transaction has been successful and to complete the transaction you have to fire a commit
query after inserting the data into the table. Because Oracle database is not on auto commit mode by default.
Solution:
Go to SQL PLUS and follow the following queries..
SQL*Plus: Release 11.2.0.1.0 Production on Tue Nov 28 15:29:43 2017
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Enter user-name: scott
Enter password:
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> desc empdetails;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NUMBER(38)
ENAME VARCHAR2(20)
SAL FLOAT(126)
SQL> insert into empdetails values(1010,'John',45000.00);
1 row created.
SQL> commit;
Commit complete.
Ensure you have Project | Build Automatically flagged. I ran into this issue too and turning that on fixed the problem.
The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute
<input type="text" name="text_box_1" placeholder="My Default Value" />
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
The M2_HOME
environment variable for the global one. See Settings Reference:
The
settings
element in thesettings.xml
file contains elements used to define values which configure Maven execution in various ways, like thepom.xml
, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:
- The Maven install:
$M2_HOME/conf/settings.xml
- A user's install:
${user.home}/.m2/settings.xml
Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
import difflib
lines1 = '''
dog
cat
bird
buffalo
gophers
hound
horse
'''.strip().splitlines()
lines2 = '''
cat
dog
bird
buffalo
gopher
horse
mouse
'''.strip().splitlines()
# Changes:
# swapped positions of cat and dog
# changed gophers to gopher
# removed hound
# added mouse
for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):
print line
Outputs the following:
--- file1
+++ file2
@@ -1,7 +1,7 @@
+cat
dog
-cat
bird
buffalo
-gophers
-hound
+gopher
horse
+mouse
This diff gives you context -- surrounding lines to help make it clear how the file is different. You can see "cat" here twice, because it was removed from below "dog" and added above it.
You can use n=0 to remove the context.
for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
print line
Outputting this:
--- file1
+++ file2
@@ -0,0 +1 @@
+cat
@@ -2 +2,0 @@
-cat
@@ -5,2 +5 @@
-gophers
-hound
+gopher
@@ -7,0 +7 @@
+mouse
But now it's full of the "@@" lines telling you the position in the file that has changed. Let's remove the extra lines to make it more readable.
for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
for prefix in ('---', '+++', '@@'):
if line.startswith(prefix):
break
else:
print line
Giving us this output:
+cat
-cat
-gophers
-hound
+gopher
+mouse
Now what do you want it to do? If you ignore all removed lines, then you won't see that "hound" was removed. If you're happy just showing the additions to the file, then you could do this:
diff = difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0)
lines = list(diff)[2:]
added = [line[1:] for line in lines if line[0] == '+']
removed = [line[1:] for line in lines if line[0] == '-']
print 'additions:'
for line in added:
print line
print
print 'additions, ignoring position'
for line in added:
if line not in removed:
print line
Outputting:
additions:
cat
gopher
mouse
additions, ignoring position:
gopher
mouse
You can probably tell by now that there are various ways to "print the differences" of two files, so you will need to be very specific if you want more help.
If supported by your browser, you may use CSS3 :read-only
selector:
input[type="text"]:read-only {
cursor: normal;
background-color: #f8f8f8;
color: #999;
}
There is nothing like kafka --version
at this point. So you should either check the version from your kafka/libs/
folder or you can run
find ./libs/ -name \*kafka_\* | head -1 | grep -o '\kafka[^\n]*'
from your kafka folder (and it will do the same for you). It will return you something like kafka_2.9.2-0.8.1.1.jar.asc
where 0.8.1.1
is your kafka version.
use app.render
in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.
We can add these two lines into DbContext class constructor to disable Self referencing loop, like
public TestContext()
: base("name=TestContext")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
Can anyone give me a brief explanation...
Sure.
ORM stands for "Object to Relational Mapping" where
The Object part is the one you use with your programming language ( python in this case )
The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )
And finally the Mapping part is where you do a bridge between your objects and your tables.
In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.
So let's say you have this object.
class Employee:
def __init__( self, name ):
self.__name = name
def getName( self ):
return self.__name
#etc.
and the table
create table employee(
name varcar(10),
-- etc
)
Using an ORM framework would allow you to map that object with a db record automagically and write something like:
emp = Employee("Ryan")
orm.save( emp )
And have the employee inserted into the DB.
Oops it was not that brief but I hope it is simple enough to catch other articles you read.
I just had the same problem, where SignOut() seemingly failed to properly remove the ticket. But only in a specific case, where some other logic caused a redirect. After I removed this second redirect (replaced it with an error message), the problem went away.
The problem must have been that the page redirected at the wrong time, hence not triggering authentication.
I think what you want is to set the android:layout_weight,
http://developer.android.com/resources/tutorials/views/hello-linearlayout.html
something like this (I'm just putting text views above and below as placeholders):
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="68"/>
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="16"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="16"/>
</LinearLayout>
update
update
ngComponentOutlet
was added to 4.0.0-beta.3
update
There is a NgComponentOutlet
work in progress that does something similar https://github.com/angular/angular/pull/11235
RC.7
// Helper component to add dynamic components
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
@Input() type: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized:boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Usage example
// Use dcl-wrapper component
@Component({
selector: 'my-tabs',
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
entryComponents: [C1, C2, C3],
bootstrap: [ App ]
})
export class AppModule {}
See also angular.io DYNAMIC COMPONENT LOADER
older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This changed again in Angular2 RC.5
I will update the example below but it's the last day before vacation.
This Plunker example demonstrates how to dynamically create components in RC.5
Update - use ViewContainerRef.createComponent()
Because DynamicComponentLoader
is deprecated, the approach needs to be update again.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Plunker example RC.4
Plunker example beta.17
Update - use loadNextToLocation
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private dcl:DynamicComponentLoader) {}
updateComponent() {
// should be executed every time `type` changes but not before `ngAfterViewInit()` was called
// to have `target` initialized
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
original
Not entirely sure from your question what your requirements are but I think this should do what you want.
The Tabs
component gets an array of types passed and it creates "tabs" for each item in the array.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
@Input() type;
ngOnChanges() {
if(this.cmpRef) {
this.cmpRef.dispose();
}
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'c1',
template: `<h2>c1</h2>`
})
export class C1 {
}
@Component({
selector: 'c2',
template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({
selector: 'c3',
template: `<h2>c3</h2>`
})
export class C3 {
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
directives: [Tabs]
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
types = [C3, C1, C2, C3, C3, C1, C1];
}
Plunker example beta.15 (not based on your Plunker)
There is also a way to pass data along that can be passed to the dynamically created component like (someData
would need to be passed like type
)
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
cmpRef.instance.someProperty = someData;
this.cmpRef = cmpRef;
});
There is also some support to use dependency injection with shared services.
For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html
Not the best way but If you are using mac or linux even in windows you can set alias for different registries.
##############NPM ALIASES######################
alias npm-default='npm config set registry https://registry.npmjs.org'
alias npm-sinopia='npm config set registry http://localhost:4873/'
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
def some_view(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks'/)
else:
form = SomeForm()
return render(request, 'some_form.html', {'form': form})
You can create your own prototype to do this:
something like:
Array.prototype.indexOfObject = function (object) {
for (var i = 0; i < this.length; i++) {
if (JSON.stringify(this[i]) === JSON.stringify(object))
return i;
}
}
I had a case where the error was thrown by a
$state.go('');
Which is obvious. I guess this can help someone in future.
Try this site http://www.sharelinkgenerator.com/. Hope this helps.
Just use date
and trusty seconds:
As you rightly point out, a lot of the details about the underlying computation are hidden if you rely on English time arithmetic. E.g. -d yesterday
, and -d 1 day ago
will have different behaviour.
Instead, you can reliably depend on the (precisely documented) seconds since the unix epoch UTC, and bash arithmetic to obtain the moment you want:
date -d @$(( $(date +"%s") - 24*3600)) +"%Y-%m-%d"
This was pointed out in another answer. This form is more portable across platforms with different date
command line flags, is language-independent (e.g. "yesterday" vs "hier" in French locale), and frankly (in the long-term) will be easier to remember, because well, you know it already. You might otherwise keep asking yourself: "Was it -d 2 hours ago
or -d 2 hour ago
again?" or "Is it -d yesterday
or -d 1 day ago
that I want?"). The only tricky bit here is the @
.
Armed with bash and nothing else:
Bash solely on bash, you can also get yesterday's time, via the printf builtin:
%(datefmt)T
causes printf to output the date-time string resulting from using
datefmt as a format string for strftime(3). The corresponding argu-
ment is an integer representing the number of seconds since the
epoch. Two special argument values may be used: -1 represents the
current time, and -2 represents the time the shell was invoked.
If no argument is specified, conversion behaves as if -1 had
been given.
This is an exception to the usual printf behavior.
So,
# inner printf gets you the current unix time in seconds
# outer printf spits it out according to the format
printf "%(%Y-%m-%d)T\n" $(( $(printf "%(%s)T" -1) - 24*3600 ))
or, equivalently with a temp variable (outer subshell optional, but keeps environment vars clean).
(
now=$(printf "%(%s)T" -1);
printf "%(%Y-%m-%d)T\n" $((now - 24*3600));
)
Note: despite the manpage stating that no argument to the %()T
formatter will assume a default -1
, i seem to get a 0 instead (thank you, bash manual version 4.3.48)
The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb")
. Returning a promise from an onFulfilled()
handler kicks off promise resolution. That's how promise chaining works.
I think it is totally independent. Just install them, then you have the commands e.g. /usr/bin/python2.5
and /usr/bin/python2.6
. Link /usr/bin/python
to the one you want to use as default.
All the libraries are in separate folders (named after the version) anyway.
If you want to compile the versions manually, this is from the readme file of the Python source code:
Installing multiple versions
On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (--prefix argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using "make altinstall" contain the major and minor version and can thus live side-by-side. "make install" also creates ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using "make install". Install all other versions using "make altinstall".
For example, if you want to install Python 2.5, 2.6 and 3.0 with 2.6 being the primary version, you would execute "make install" in your 2.6 build directory and "make altinstall" in the others.
Yah Im pretty sure you just put
break;
right where you want it to exit
like
if (variable == 1)
{
//do something
}
else
{
//exit
break;
}
Edit 2
I finally found a solution by implementing my forward action like that:
private void applyForward() {
FacesContext facesContext = FacesContext.getCurrentInstance();
// Find where to redirect the user.
String redirect = getTheFromOutCome();
// Change the Navigation context.
NavigationHandler myNav = facesContext.getApplication().getNavigationHandler();
myNav.handleNavigation(facesContext, null, redirect);
// Update the view root
UIViewRoot vr = facesContext.getViewRoot();
if (vr != null) {
// Get the URL where to redirect the user
String url = facesContext.getExternalContext().getRequestContextPath();
url = url + "/" + vr.getViewId().replace(".xhtml", ".jsf");
Object obj = facesContext.getExternalContext().getResponse();
if (obj instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse) obj;
try {
// Redirect the user now.
response.sendRedirect(response.encodeURL(url));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It works (at least regarding my first tests), but I still don't like the way it is implemented... Any better idea?
Edit This solution does not work. Indeed, when the doForward()
function is called, the JSF lifecycle has already been started, and then recreate a new request is not possible.
One idea to solve this issue, but I don't really like it, is to force the doForward()
action during one of the setBindedInputHidden()
method:
private boolean actionDefined = false;
private boolean actionParamDefined = false;
public void setHiddenActionParam(HtmlInputHidden hiddenActionParam) {
this.hiddenActionParam = hiddenActionParam;
String actionParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("actionParam");
this.hiddenActionParam.setValue(actionParam);
actionParamDefined = true;
forwardAction();
}
public void setHiddenAction(HtmlInputHidden hiddenAction) {
this.hiddenAction = hiddenAction;
String action = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("action");
this.hiddenAction.setValue(action);
actionDefined = true;
forwardAction();
}
private void forwardAction() {
if (!actionDefined || !actionParamDefined) {
// As one of the inputHidden was not binded yet, we do nothing...
return;
}
// Now, both action and actionParam inputHidden are binded, we can execute the forward...
doForward(null);
}
This solution does not involve any Javascript call, and works does not work.
You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:
>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'
This would of course fail if there is multiple numbers in the input. a quick check would be:
assert(age in input_given)
and also:
assert(len(name)<len(input_given))
Probably your problem is that for Docker that has been installed from default Ubuntu repository, the package name is docker.io
Or package name may be something like docker-ce
.
Try running
dpkg -l | grep -i docker
to identify what installed package you have
So you need to change package name in commands from https://stackoverflow.com/a/31313851/2340159 to match package name. For example, for docker.io
it would be:
sudo apt-get purge -y docker.io
sudo apt-get autoremove -y --purge docker.io
sudo apt-get autoclean
It adds:
The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:
sudo rm -rf /var/lib/docker
Remove docker from apparmor.d:
sudo rm /etc/apparmor.d/docker
Remove docker group:
sudo groupdel docker
If you are trying to capitalize the first letter of each word in an array you can simply put this:
array_name.map(&:capitalize)
The .on()
method is used to delegate events to elements, dynamically added or already present in the DOM:
// STATIC-PARENT on EVENT DYNAMIC-CHILD_x000D_
$('#registered_participants').on('click', '.new_participant_form', function() {_x000D_
_x000D_
var $td = $(this).closest('tr').find('td');_x000D_
var part_name = $td.eq(1).text();_x000D_
console.log( part_name );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$('#add_new_participant').click(function() {_x000D_
_x000D_
var first_name = $.trim( $('#f_name_participant').val() );_x000D_
var last_name = $.trim( $('#l_name_participant').val() );_x000D_
var role = $('#new_participant_role').val();_x000D_
var email = $('#email_participant').val();_x000D_
_x000D_
if(!first_name && !last_name) return;_x000D_
_x000D_
$('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');_x000D_
_x000D_
});
_x000D_
<table id="registered_participants" class="tablesorter">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Form</th>_x000D_
<th>Name</th>_x000D_
<th>Role</th>_x000D_
<th>Progress </th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td><a href="#" class="new_participant_form">Participant Registration</a></td>_x000D_
<td>Smith Johnson</td>_x000D_
<td>Parent</td>_x000D_
<td>60% done</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<input type="text" id="f_name_participant" placeholder="Name">_x000D_
<input type="text" id="l_name_participant" placeholder="Surname">_x000D_
<select id="new_participant_role">_x000D_
<option>Parent</option>_x000D_
<option>Child</option>_x000D_
</select>_x000D_
<button id="add_new_participant">Add New Entry</button>_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Read more: http://api.jquery.com/on/
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
Use this method:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
How to use it:
string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
The express.static
middleware is separate from res.sendFile
, so initializing it with an absolute path to your public
directory won't do anything to res.sendFile
. You need to use an absolute path directly with res.sendFile
. There are two simple ways to do it:
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
res.sendFile('index1.html', { root: path.join(__dirname, '../public') });
Note: __dirname
returns the directory that the currently executing script is in. In your case, it looks like server.js
is in app/
. So, to get to public
, you'll need back out one level first: ../public/index1.html
.
Note: path
is a built-in module that needs to be require
d for the above code to work: var path = require('path');
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.
With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.
I've found the answer from these two websites: Net Maniac and Aimred.
You need to have version > 0.8 of rake to use this technique
The normal rake task description is this:
desc 'Task Description'
task :task_name => [:depends_on_taskA, :depends_on_taskB] do
#interesting things
end
To pass arguments, do three things:
To access the arguments in the script, use args.arg_name
desc 'Takes arguments task'
task :task_name, :display_value, :display_times, :needs => [:depends_on_taskA, :depends_on_taskB] do |t, args|
args.display_times.to_i.times do
puts args.display_value
end
end
To call this task from the command line, pass it the arguments in []s
rake task_name['Hello',4]
will output
Hello
Hello
Hello
Hello
and if you want to call this task from another task, and pass it arguments, use invoke
task :caller do
puts 'In Caller'
Rake::Task[:task_name].invoke('hi',2)
end
then the command
rake caller
will output
In Caller
hi
hi
I haven't found a way to pass arguments as part of a dependency, as the following code breaks:
task :caller => :task_name['hi',2]' do
puts 'In Caller'
end
use
python manage.py dumpdata
then look at the end you will find the user name
Instead of using success
, I change it to then
and it works.
here is the code:
lgrg.controller('login', function($scope, $window, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$scope.errorInfo = null
$http({
method : 'POST',
url : '/login',
headers : {'Content-Type': 'application/json'}
data: $scope.loginUser
}).then(function(data) {
if (!data.status) {
$scope.errorInfo = data.info
} else {
//page jump
$window.location.href = '/admin';
}
});
};
});
As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:
> str(list_all)
List of 2
$ :List of 2
..$ : num 1
..$ : num 2
$ :List of 2
..$ : chr "a"
..$ : chr "b"
And the most simple construction would be this:
> str(list(list(1, 2), list("a", "b")))
List of 2
$ :List of 2
..$ : num 1
..$ : num 2
$ :List of 2
..$ : chr "a"
..$ : chr "b"
There is another way of doing it or if you wish to move back to more than just one commit.
Here is a an example to move back to n
number of commits:
git branch topic master~n
For the sake of this question, this can also be done:
git branch topic master~1
The command works perfectly on git version 2.7.4
. Haven't tested it on any other version.
Note, you may also be interested in:
Custom web font not working in IE9
Which includes a more descriptive breakdown of the CSS you see below (and explains the tweaks that make it work better on IE6-9).
@font-face {
font-family: 'Bumble Bee';
src: url('bumblebee-webfont.eot');
src: local('?'),
url('bumblebee-webfont.woff') format('woff'),
url('bumblebee-webfont.ttf') format('truetype'),
url('bumblebee-webfont.svg#webfontg8dbVmxj') format('svg');
}
@font-face {
font-family: 'GestaReFogular';
src: url('gestareg-webfont.eot');
src: local('?'),
url('gestareg-webfont.woff') format('woff'),
url('gestareg-webfont.ttf') format('truetype'),
url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}
body {
background: #fff url(../images/body-bg-corporate.gif) repeat-x;
padding-bottom: 10px;
font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}
h1 {
font-family: "Bumble Bee", "Times New Roman", Georgia, Serif;
}
And your follow-up questions:
Q. I would like to use a font such as "Bumble bee," for example. How can I use
@font-face
to make that font available on the user's computer?
Note that I don't know what the name of your Bumble Bee font or file is, so adjust accordingly, and that the font-face declaration should precede (come before) your use of it, as I've shown above.
Q. Can I still use the other
@font-face
typeface "GestaRegular" as well? Can I use both in the same stylesheet?
Just list them together as I've shown in my example. There is no reason you can't declare both. All that @font-face
does is instruct the browser to download and make a font-family available. See: http://iliadraznin.com/2009/07/css3-font-face-multiple-weights
In TensorFlow 2.0, you can use tf.config.experimental.list_physical_devices('GPU')
:
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
print("Name:", gpu.name, " Type:", gpu.device_type)
If you have two GPUs installed, it outputs this:
Name: /physical_device:GPU:0 Type: GPU
Name: /physical_device:GPU:1 Type: GPU
From 2.1, you can drop experimental
:
gpus = tf.config.list_physical_devices('GPU')
See:
Cleaner way to remove those spaces is by using float: left;
:
HTML:
<div>Some Text</div>
<div>Some Text</div>
CSS:
div {
background-color: red;
float: left;
}
I'ts supported in all new browsers. Never got it why back when IE ruled lot's of developers didn't make sue their site works well on firefox/chrome, but today, when IE is down to 14.3 %. anyways, didn't have many issues in IE-9 even thought it's not supported, for example the above demo works fine.
There are all sorts of things which can do this. One possiblity is "Traffic Shaping". This is commonly done in office environments to reserve bandwidth for business critical activities. It may also be done by the web hosting company, or by your ISP, for very similar reasons.
You can also set it up at home very simply.
For example there may be a rule reserving minimum bandwidth for FTP, while SFTP might be falling under an "everything else" rule. Or there might be a rule capping bandwidth for SFTP, but someone else is also using SFTP at the same time as you.
So: Where are you tranferring the file from and to?
PyPDF2 does work, but results may vary. I am seeing quite inconsistent findings from its result extraction.
reader=PyPDF2.pdf.PdfFileReader(self._path)
eachPageText=[]
for i in range(0,reader.getNumPages()):
pageText=reader.getPage(i).extractText()
print(pageText)
eachPageText.append(pageText)
If you check Thrown
for Common Language Runtime Exception
in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.
This will probably give you some insight into what is going on.
Simple Right Click and go to Properties Option of any project on your Existing application and see the Application option on Left menu and then click on Application option see target Framework to see current Framework version .
canonical representation means view the character in different style for example if I write a letter A means another person may write the letter A in different style:)
This is according to OPTICAL CHARACTER RECOGNITION FIELD
For my mac Big Sur, with gist from answers above, following steps work for me.
$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa
And added ssh public key to git hub by following instruction;
If all gone well, you should be able to get the following result;
$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...
As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.
From Here
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.You could use a List<T>
and when T
is a value type it will be allocated in contiguous memory which would not be the case if T
is a reference type.
Example:
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);
int someElement = integers[1];
Try this:
String after = before.trim().replaceAll(" +", " ");
String.trim()
trim()
regexIt's also possible to do this with just one replaceAll
, but this is much less readable than the trim()
solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
There are 3 alternates:
^_+
: any sequence of spaces at the beginning of the string
$1
, which captures the empty string_+$
: any sequence of spaces at the end of the string
$1
, which captures the empty string(_)+
: any sequence of spaces that matches none of the above, meaning it's in the middle
$1
, which captures a single spaceHere is a link that will help answer your questions. In short:
count(*) is the correct way to write it and count(1) is OPTIMIZED TO BE count(*) internally -- since
a) count the rows where 1 is not null is less efficient than
b) count the rows
We used DBVisualizer for that.
Description: The references graph is a great feature as it automatically renders all primary/foreign key mappings (also called referential integrity constraints) in a graph style. The table nodes and relations are layed out automatically, with a number of layout modes available. The resulting graph is unique as it displays all information in an optimal and readable layout. from its site
I've created the API "generator-excel" to create an Excel file, below the dependecy:
<dependency>
<groupId>com.github.bld-commons.excel</groupId>
<artifactId>generator-excel</artifactId>
<version>3.1.0</version>
</dependency>
This library can to configure the styles, the functions, the charts, the pivot table and etc. through a series of annotations.
You can write rows by getting data from a datasource trough a query with or without parameters.
Below an example to develop
package bld.generator.report.junit.entity;
import java.util.Date;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import bld.generator.report.excel.RowSheet;
import bld.generator.report.excel.annotation.ExcelCellLayout;
import bld.generator.report.excel.annotation.ExcelColumn;
import bld.generator.report.excel.annotation.ExcelDate;
import bld.generator.report.excel.annotation.ExcelImage;
import bld.generator.report.excel.annotation.ExcelRowHeight;
@ExcelRowHeight(height = 3)
public class UtenteRow implements RowSheet {
@ExcelColumn(columnName = "Id", indexColumn = 0)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
private Integer idUtente;
@ExcelColumn(columnName = "Nome", indexColumn = 2)
@ExcelCellLayout
private String nome;
@ExcelColumn(columnName = "Cognome", indexColumn = 1)
@ExcelCellLayout
private String cognome;
@ExcelColumn(columnName = "Data di nascita", indexColumn = 3)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
@ExcelDate
private Date dataNascita;
@ExcelColumn(columnName = "Immagine", indexColumn = 4)
@ExcelCellLayout
@ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
private byte[] image;
@ExcelColumn(columnName = "Path", indexColumn = 5)
@ExcelCellLayout
@ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
private String path;
public UtenteRow() {
}
public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) {
super();
this.idUtente = idUtente;
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public Integer getIdUtente() {
return idUtente;
}
public void setIdUtente(Integer idUtente) {
this.idUtente = idUtente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public Date getDataNascita() {
return dataNascita;
}
public void setDataNascita(Date dataNascita) {
this.dataNascita = dataNascita;
}
public byte[] getImage() {
return image;
}
public String getPath() {
return path;
}
public void setImage(byte[] image) {
this.image = image;
}
public void setPath(String path) {
this.path = path;
}
}
package bld.generator.report.junit.entity;
import org.apache.poi.ss.usermodel.DataConsolidateFunction;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import bld.generator.report.excel.RowSheet;
import bld.generator.report.excel.annotation.ExcelCellLayout;
import bld.generator.report.excel.annotation.ExcelColumn;
import bld.generator.report.excel.annotation.ExcelFont;
import bld.generator.report.excel.annotation.ExcelSubtotal;
import bld.generator.report.excel.annotation.ExcelSubtotals;
@ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total")
public class SalaryRow implements RowSheet {
@ExcelColumn(columnName = "Name", indexColumn = 0)
@ExcelCellLayout
private String name;
@ExcelColumn(columnName = "Amount", indexColumn = 1)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
@ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true)))
private Double amount;
public SalaryRow() {
super();
}
public SalaryRow(String name, Double amount) {
super();
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
}
package bld.generator.report.junit.entity;
import javax.validation.constraints.Size;
import bld.generator.report.excel.QuerySheetData;
import bld.generator.report.excel.annotation.ExcelHeaderLayout;
import bld.generator.report.excel.annotation.ExcelMarginSheet;
import bld.generator.report.excel.annotation.ExcelQuery;
import bld.generator.report.excel.annotation.ExcelSheetLayout;
@ExcelSheetLayout
@ExcelHeaderLayout
@ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5)
@ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path "
+ "FROM utente "
+ "WHERE cognome=:cognome "
+ "order by cognome,nome")
public class UtenteSheet extends QuerySheetData<UtenteRow> {
public UtenteSheet(@Size(max = 31) String sheetName) {
super(sheetName);
}
}
package bld.generator.report.junit.entity;
import javax.validation.constraints.Size;
import bld.generator.report.excel.SheetData;
import bld.generator.report.excel.annotation.ExcelHeaderLayout;
import bld.generator.report.excel.annotation.ExcelMarginSheet;
import bld.generator.report.excel.annotation.ExcelSheetLayout;
@ExcelSheetLayout
@ExcelHeaderLayout
@ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5)
public class SalarySheet extends SheetData<SalaryRow> {
public SalarySheet(@Size(max = 31) String sheetName) {
super(sheetName);
}
}
package bld.generator.report.junit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import bld.generator.report.excel.BaseSheet;
import bld.generator.report.excel.GenerateExcel;
import bld.generator.report.excel.data.ReportExcel;
import bld.generator.report.junit.entity.AutoreLibriSheet;
import bld.generator.report.junit.entity.CasaEditrice;
import bld.generator.report.junit.entity.GenereSheet;
import bld.generator.report.junit.entity.SalaryRow;
import bld.generator.report.junit.entity.SalarySheet;
import bld.generator.report.junit.entity.TotaleAutoreLibriRow;
import bld.generator.report.junit.entity.TotaleAutoreLibriSheet;
import bld.generator.report.junit.entity.UtenteSheet;
import bld.generator.report.utils.ExcelUtils;
/**
* The Class ReportTest.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties
@ComponentScan(basePackages = {"bld.generator","bld.read"})
@EnableTransactionManagement
public class ReportTestJpa {
/** The Constant PATH_FILE. */
private static final String PATH_FILE = "/mnt/report/";
/** The generate excel. */
@Autowired
private GenerateExcel generateExcel;
/**
* Sets the up.
*
* @throws Exception the exception
*/
@Before
public void setUp() throws Exception {
}
/**
* Test.
*
* @throws Exception the exception
*/
@Test
public void test() throws Exception {
List<BaseSheet> listBaseSheet = new ArrayList<>();
UtenteSheet utenteSheet=new UtenteSheet("Utente");
utenteSheet.getMapParameters().put("cognome", "Rossi");
listBaseSheet.add(utenteSheet);
CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico");
listBaseSheet.add(casaEditrice);
AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label");
TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet();
totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale"));
autoreLibriSheet.setSheetFunctionsTotal(totaleAutoreLibriSheet);
listBaseSheet.add(autoreLibriSheet);
GenereSheet genereSheet=new GenereSheet("Genere");
listBaseSheet.add(genereSheet);
SalarySheet salarySheet=new SalarySheet("salary");
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
listBaseSheet.add(salarySheet);
ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet);
byte[] byteReport = this.generateExcel.createFileXlsx(excel);
ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport);
}
}
logging:
level:
root: WARN
org:
springframework:
web: DEBUG
hibernate: ERROR
spring:
datasource:
url: jdbc:postgresql://localhost:5432/excel_db
username: ${EXCEL_USER_DB}
password: ${EXCEL_PASSWORD_DB}
jpa:
show-sql: true
properties:
hibernate:
default_schema: public
jdbc:
lob:
non_contextual_creation: true
format_sql: true
ddl-auto: auto
database-platform: org.hibernate.dialect.PostgreSQLDialect
generate-ddl: true
below the link of the project on github:
Easy way of doing it would be:
<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">
Works with all browsers, except IE9. I haven't tested it in IE10+.
I recalled reading about this in the standard, so here goes:
See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.
ISO/IEC 9899:201x
7.21.3 §7
At program startup, three text streams are predefined and need not be opened explicitly — standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
7.21.3 §3
When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.
This means that std::cout
and std::cin
are fully buffered if and only if they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior.
However, if std::cout.sync_with_stdio(false)
is called, then '\n'
will not cause a flush even to interactive devices. Otherwise '\n'
is equivalent to std::endl
unless piping to files: c++ ref on std::endl.
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
Another approach is using Object.defineProperty
to set value
as a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:
The HTML file:
<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>
The javascript file:
var _value = null;
Object.defineProperty($scope, 'value', {
get: function () {
return _value;
},
set: function (value) {
_value = value;
someFunction();
}
});
see this plunker for the implementation
class Exception
{
public Exception(string message)
{
[...]
}
}
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
: base(message)
{
[...]
}
}
For @return
tag use {{field1: Number, field2: String}}
, see: http://wiki.servoy.com/display/public/DOCS/Annotating+JavaScript+using+JSDoc
I have tried Alberthoven's example (hibernate-validator 4.0.2.GA) and i get an ValidationException: „Annotated methods must follow the JavaBeans naming convention. match() does not.“ too. After I renamed the method from „match“ to "isValid" it works.
public class Password {
private String password;
private String retypedPassword;
public Password(String password, String retypedPassword) {
super();
this.password = password;
this.retypedPassword = retypedPassword;
}
@AssertTrue(message="password should match retyped password")
private boolean isValid(){
if (password == null) {
return retypedPassword == null;
} else {
return password.equals(retypedPassword);
}
}
public String getPassword() {
return password;
}
public String getRetypedPassword() {
return retypedPassword;
}
}
Nice implementation for material design circular progress bar (from rahatarmanahmed/CircularProgressView),
<com.github.rahatarmanahmed.cpv.CircularProgressView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/progress_view"
android:layout_width="40dp"
android:layout_height="40dp"
app:cpv_indeterminate="true"/>
In my case i declared a function in COM Control .idl
file like
[id(1)] HRESULT MyMethod([in]INT param);
but not declared in my interface .h
file like this
STDMETHOD(MyMethod)(INT param);
Problem solved by adding above line into my interface .h file
this might help some one .
After becoming frustrated with the too many limitations of cut
, I wrote my own replacement, which I called cuts
for "cut on steroids".
cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.
One example, out of many, addressing this particular question:
$ cat text.txt
0 1 2 3
0 1 2 3 4
$ cuts 2 text.txt
2
2
cuts
supports:
paste
separately)and much more. None of which is provided by standard cut
.
See also: https://stackoverflow.com/a/24543231/1296044
Source and documentation (free software): http://arielf.github.io/cuts/
The answer might be inappropriate, but I hope it helps you
class DisableCSRFOnDebug(object):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
Having middleware like this helps to debug requests and to check csrf in production servers.
How to set the python version back to 2.7 if you have installed Anaconda3 (Python 3.6) on MacOS High Sierra 10.13.5
Edit the .bash_profile file in your home directory.
vi $HOME/.bash_profile
hash out the line # export PATH="/Users/YOURUSERNAME/anaconda3/bin:$PATH"
Close the shell open again you should see 2.7 when you run python.
Then if you want 3.6 you can simply uncomment your anaconda3 line in your bash profile.
Trying to unlink python will end in tears in Mac OSX.
You will something like this
unlink: /usr/bin/python: Operation not permitted
Hope that helps someone out !! :) :)
I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.
Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.
Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.
This is how I have done in Swift 3.0. I created UIView extension and calling the self.view.showToast(message: "Message Here", duration: 3.0) and self.view.hideToast()
extension UIView{
var showToastTag :Int {return 999}
//Generic Show toast
func showToast(message : String, duration:TimeInterval) {
let toastLabel = UILabel(frame: CGRect(x:0, y:0, width: (self.frame.size.width)-60, height:64))
toastLabel.backgroundColor = UIColor.gray
toastLabel.textColor = UIColor.black
toastLabel.numberOfLines = 0
toastLabel.layer.borderColor = UIColor.lightGray.cgColor
toastLabel.layer.borderWidth = 1.0
toastLabel.textAlignment = .center;
toastLabel.font = UIFont(name: "HelveticaNeue", size: 17.0)
toastLabel.text = message
toastLabel.center = self.center
toastLabel.isEnabled = true
toastLabel.alpha = 0.99
toastLabel.tag = showToastTag
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.addSubview(toastLabel)
UIView.animate(withDuration: duration, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.95
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
//Generic Hide toast
func hideToast(){
if let view = self.viewWithTag(self.showToastTag){
view.removeFromSuperview()
}
}
}
Demo:
$exePath = $env:NGINX_HOME + '/nginx.exe'
$myArgs = $args.Clone()
$myArgs += '-p'
$myArgs += $env:NGINX_HOME
& $exepath $myArgs
Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.
Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.
You can even edit most of the code while it is running.
Use Debug.Print
to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox
.
Use breakpoints or the Stop
keyword to automatically halt execution in interesting areas.
You can use Debug.Assert
to halt execution conditionally.
If that is a copy/paste from your script, you've permuted this line:
#!/usr/env/bin bash
There's no #!/usr/env/bin
, you meant #!/usr/bin/env
.
Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.
You have to catch the SIGINT signal (we are talking POSIX right?)
See @Gab Royer´s answer for sigaction.
Example:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void my_handler(sig_t s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
signal (SIGINT,my_handler);
while(1);
return 0;
}
Try shoes. Unfortunately, I have not had a chance to work with it yet, but I have an upcoming project where I plan to use it. It is cross-platform. Also the API looks very Rubyish so I would give it a try.
If you are just switching the image between the real color and the black-and-white, you can set one selector as:
{filter:none;}
and another as:
{filter:grayscale(100%);}
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
If your string contains non-ASCII characters - it's better to do it this way:
s.toUtf8().data()
(or s->toUtf8().data()
)
If you have the sqlite database, use the sqlite3 command line program and these commands:
To list all the tables in the database:
.tables
To show the schema for a given tablename
:
.schema tablename
There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).
The onbeforeunload
event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).
Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).
In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.
An example of how I use it (pseudo code):
onbeforeunload = function() {
if(Application.hasUnsavedChanges()) {
return 'You have unsaved changes. Please save them before leaving this page';
}
};
If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.
There is also an option to use Handler -> postDelayed
Handler().postDelayed({
//doSomethingHere()
}, 1000)
Here is a way that has worked for me and has allowed me keep my environment variables DRY by reusing a json file.
const webpack = require('webpack');
let config = require('./settings.json');
if (__PROD__) {
config = require('./settings-prod.json');
}
const envVars = {};
Object.keys(config).forEach((key) => {
envVars[key] = JSON.stringify(config[key]);
});
new webpack.DefinePlugin({
'process.env': envVars
}),
public static String getIntervalTime(long longInterval) {
long intMillis = longInterval;
long dd = TimeUnit.MILLISECONDS.toDays(intMillis);
long daysMillis = TimeUnit.DAYS.toMillis(dd);
intMillis -= daysMillis;
long hh = TimeUnit.MILLISECONDS.toHours(intMillis);
long hoursMillis = TimeUnit.HOURS.toMillis(hh);
intMillis -= hoursMillis;
long mm = TimeUnit.MILLISECONDS.toMinutes(intMillis);
long minutesMillis = TimeUnit.MINUTES.toMillis(mm);
intMillis -= minutesMillis;
long ss = TimeUnit.MILLISECONDS.toSeconds(intMillis);
long secondsMillis = TimeUnit.SECONDS.toMillis(ss);
intMillis -= secondsMillis;
String stringInterval = "%02d days - %02d:%02d:%02d.%03d";
return String.format(stringInterval , dd, hh, mm, ss, intMillis);
}
Testing
long delay = 1000*60*20 + 1000*5 + 10;
LOGGER.log(Level.INFO, "Delay Expected {0}", getIntervalTime(delay));
Output
INFO: Delay Expected 00 days - 00:20:05.010
to_char(timestamp, 'YYYY-MM')
You say that the order is not "right", but I cannot see why it is wrong (at least until year 10000 comes around).
<input type="file" onchange="getBaseUrl()">
function getBaseUrl () {
var file = document.querySelector('input[type=file]')['files'][0];
var reader = new FileReader();
var baseString;
reader.onloadend = function () {
baseString = reader.result;
console.log(baseString);
};
reader.readAsDataURL(file);
}
My two cents here. If you know the properties are in the same order, you can stringify the elements and remove dupes from the array and parse the array again. Something like this:
var things = new Object();
things.thing = new Array();
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});
let stringified = things.thing.map(i=>JSON.stringify(i));
let unique = stringified.filter((k, idx)=> stringified.indexOf(k) === idx)
.map(j=> JSON.parse(j))
console.log(unique);
_x000D_
In my case, it was the open_basedir which was defined. I commented it out (default) and my issue was resolved. I can now set the upload directory anywhere.
You can try as.vector(t(test))
. Please note that, if you want to do it by columns you should use unlist(test)
.
My test string for the following:
testing='12345,abc,123,54321,ab15234,123456,52341';
If I understand your question, you'd want ["12345", "54321", "15234", "52341"]
.
If JS engines supported regexp lookbehinds, you could do:
testing.match(/(?<!\d)\d{5}(?!\d)/g)
Since it doesn't currently, you could:
testing.match(/(?:^|\D)(\d{5})(?!\d)/g)
and remove the leading non-digit from appropriate results, or:
pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
result.push(match[1]);
}
Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while
loop, otherwise you'll get an infinite loop.
If using TextBox2.Text
as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.
If the text box is blank when Convert.ToInt32
is called, you will receive the System.FormatException
. Suggest trying:
protected void SetImageWidth()
{
try{
Image1.Width = Convert.ToInt32(TextBox1.Text);
}
catch(System.FormatException)
{
Image1.Width = 100; // or other default value as appropriate in context.
}
}
You can't run two SQL statements into one like you are doing.
You can't "execute" a select query.
db is an object and you haven't set it to anything: (e.g. set db = currentdb)
In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.
You might want to be a bit more specific about the date you are inserting:
INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"
This works well for coping entire records.
UPDATE your_table
SET new_field = sourse_field
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username
and password
:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in
to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data);
line in the success function would alert that message. Of course, you can echo
anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script>
tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?>
at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
I write my own light implementation for image loader with using NSCache. No cell image flickering!
typealias ImageCacheLoaderCompletionHandler = ((UIImage) -> ())
class ImageCacheLoader {
var task: URLSessionDownloadTask!
var session: URLSession!
var cache: NSCache<NSString, UIImage>!
init() {
session = URLSession.shared
task = URLSessionDownloadTask()
self.cache = NSCache()
}
func obtainImageWithPath(imagePath: String, completionHandler: @escaping ImageCacheLoaderCompletionHandler) {
if let image = self.cache.object(forKey: imagePath as NSString) {
DispatchQueue.main.async {
completionHandler(image)
}
} else {
/* You need placeholder image in your assets,
if you want to display a placeholder to user */
let placeholder = #imageLiteral(resourceName: "placeholder")
DispatchQueue.main.async {
completionHandler(placeholder)
}
let url: URL! = URL(string: imagePath)
task = session.downloadTask(with: url, completionHandler: { (location, response, error) in
if let data = try? Data(contentsOf: url) {
let img: UIImage! = UIImage(data: data)
self.cache.setObject(img, forKey: imagePath as NSString)
DispatchQueue.main.async {
completionHandler(img)
}
}
})
task.resume()
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier")
cell.title = "Cool title"
imageLoader.obtainImageWithPath(imagePath: viewModel.image) { (image) in
// Before assigning the image, check whether the current cell is visible
if let updateCell = tableView.cellForRow(at: indexPath) {
updateCell.imageView.image = image
}
}
return cell
}
%W
and %w
allow you to create an Array of strings without using quotes and commas.
Taking a certain liberty with the requirements, you're looking for
\d+([\d,]?\d)*(\.\d+)?
But notice this will match e.g. 11,11,1
Try this:
Html Markup
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">HyperLink</asp:HyperLink>
Code
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
protected void Page_Load(object sender, EventArgs e)
{
Style style = new Style();
style.ForeColor = Color.Green;
this.Page.Header.StyleSheet.CreateStyleRule(style, this, "#" + HyperLink1.ClientID + ":hover");
}
If the value of a disabled textbox needs to be retained when a form is cleared (reset), disabled = "disabled"
has to be used, as read-only textbox will not retain the value
For Example:
HTML
Textbox
<input type="text" id="disabledText" name="randombox" value="demo" disabled="disabled" />
Reset button
<button type="reset" id="clearButton">Clear</button>
In the above example, when Clear button is pressed, disabled text value will be retained in the form. Value will not be retained in the case of input type = "text" readonly="readonly"
You could use inline styles and define the width in the <th>
tag. Make it so that the sum of the widths = 100%.
<tr>
<th style="width:10%">Size</th>
<th style="width:30%">Bust</th>
<th style="width:50%">Waist</th>
<th style="width:10%">Hips</th>
</tr>
Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
The error comes (at least sometimes) from paths that are too long. In my project simply reducing the output file path does the job: "Properties/Configuration Properties/General/Intermediate Directory"
Seems that I have hit the 250 character path limitation.
Here is a code snippet, that counts number of files in a particular HDFS directory (I used this to determine how many reducers to use in a particular ETL code). You can easily modify this to suite your needs.
private int calculateNumberOfReducers(String input) throws IOException {
int numberOfReducers = 0;
Path inputPath = new Path(input);
FileSystem fs = inputPath.getFileSystem(getConf());
FileStatus[] statuses = fs.globStatus(inputPath);
for(FileStatus status: statuses) {
if(status.isDirectory()) {
numberOfReducers += getNumberOfInputFiles(status, fs);
} else if(status.isFile()) {
numberOfReducers ++;
}
}
return numberOfReducers;
}
/**
* Recursively determines number of input files in an HDFS directory
*
* @param status instance of FileStatus
* @param fs instance of FileSystem
* @return number of input files within particular HDFS directory
* @throws IOException
*/
private int getNumberOfInputFiles(FileStatus status, FileSystem fs) throws IOException {
int inputFileCount = 0;
if(status.isDirectory()) {
FileStatus[] files = fs.listStatus(status.getPath());
for(FileStatus file: files) {
inputFileCount += getNumberOfInputFiles(file, fs);
}
} else {
inputFileCount ++;
}
return inputFileCount;
}
I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:
Public Class MyListItem
Private mText As String
Private mValue As String
Public Sub New(ByVal pText As String, ByVal pValue As String)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
Now when you want to add the items to your ComboBox you can do it like this:
myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))
Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:
Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)
One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.
Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.
Here's the new and improved GenericListItem
class:
Public Class GenericListItem(Of T)
Private mText As String
Private mValue As T
Public Sub New(ByVal pText As String, ByVal pValue As T)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As T
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
And here is how you would now add Generic items to your ComboBox. In this case an Integer:
Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))
And now the retrieval of the item:
Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())
Keep in mind that the type Integer
can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.
If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".
Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."
My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.
As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.
For a GOOD and definite solution see the Setting up Permissions
section in Installing and Configuring Symfony
section :
Setting up Permissions
One common issue when installing Symfony is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On a UNIX system, if your web server user is different from your command line user, you can try one of the following solutions.
- Use the same user for the CLI and the web server
In development environments, it is a common practice to use the same UNIX user for the CLI and the web server because it avoids any of these permissions issues when setting up new projects. This can be done by editing your web server configuration (e.g. commonly httpd.conf or apache2.conf for Apache) and setting its user to be the same as your CLI user (e.g. for Apache, update the User and Group values).
- Using ACL on a system that supports chmod +a
Many systems allow you to use the chmod +a command. Try this first, and if you get an error - try the next method. This uses a command to try to determine your web server user and set it as HTTPDUSER:
$ rm -rf app/cache/* $ rm -rf app/logs/* $ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs $ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
- Using ACL on a system that does not support chmod +a
Some systems don't support chmod +a, but do support another utility called setfacl. You may need to enable ACL support on your partition and install setfacl before using it (as is the case with Ubuntu). This uses a command to try to determine your web server user and set it as HTTPDUSER:
$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs $ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
For Symfony 3 it would be:
$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs $ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs
If this doesn't work, try adding -n option.
- Without using ACL
If none of the previous methods work for you, change the umask so that the cache and log directories will be group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console, web/app.php and web/app_dev.php files:
umask(0002); // This will let the permissions be 0775 // or umask(0000); // This will let the permissions be 0777
Note that using the ACL is recommended when you have access to them on your server because changing the umask is not thread-safe.
source : Failed to write cache file "/var/www/myapp/app/cache/dev/classes.php" when clearing the cache
It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)
norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn
fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)
annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
def update_annot(ind):
pos = sc.get_offsets()[ind["ind"][0]]
annot.xy = pos
text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))),
" ".join([names[n] for n in ind["ind"]]))
annot.set_text(text)
annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
annot.get_bbox_patch().set_alpha(0.4)
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = sc.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("motion_notify_event", hover)
plt.show()
Because people also want to use this solution for a line plot
instead of a scatter, the following would be the same solution for plot
(which works slightly differently).
import matplotlib.pyplot as plt_x000D_
import numpy as np; np.random.seed(1)_x000D_
_x000D_
x = np.sort(np.random.rand(15))_x000D_
y = np.sort(np.random.rand(15))_x000D_
names = np.array(list("ABCDEFGHIJKLMNO"))_x000D_
_x000D_
norm = plt.Normalize(1,4)_x000D_
cmap = plt.cm.RdYlGn_x000D_
_x000D_
fig,ax = plt.subplots()_x000D_
line, = plt.plot(x,y, marker="o")_x000D_
_x000D_
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",_x000D_
bbox=dict(boxstyle="round", fc="w"),_x000D_
arrowprops=dict(arrowstyle="->"))_x000D_
annot.set_visible(False)_x000D_
_x000D_
def update_annot(ind):_x000D_
x,y = line.get_data()_x000D_
annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])_x000D_
text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), _x000D_
" ".join([names[n] for n in ind["ind"]]))_x000D_
annot.set_text(text)_x000D_
annot.get_bbox_patch().set_alpha(0.4)_x000D_
_x000D_
_x000D_
def hover(event):_x000D_
vis = annot.get_visible()_x000D_
if event.inaxes == ax:_x000D_
cont, ind = line.contains(event)_x000D_
if cont:_x000D_
update_annot(ind)_x000D_
annot.set_visible(True)_x000D_
fig.canvas.draw_idle()_x000D_
else:_x000D_
if vis:_x000D_
annot.set_visible(False)_x000D_
fig.canvas.draw_idle()_x000D_
_x000D_
fig.canvas.mpl_connect("motion_notify_event", hover)_x000D_
_x000D_
plt.show()
_x000D_
In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis?
In case someone is looking for a solution for bar plots, please refer to e.g. this answer.
wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm
rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm
maybe some URL is broken,please research it. Enjoy~~
For bootstrap 3 datepicker. (Note the capital letters)
$("#datetimepicker").datetimepicker( {
format: "YYYY",
viewMode: "years"
});
Please try following
if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
echo "WORKING"
else
echo "Out of range!"
Step 1 : Open Your terminal
Step 2 : Run bellow command
curl -sS https://getcomposer.org/installer | php
Step 3 : After installation run bellow command
sudo mv composer.phar /usr/local/bin/
Step 4 : Open bash_profile file create alias follow bellow steps
vim ~/.bash_profile
Step 5 : Add bellow line in bash_profile file
alias composer="php /usr/local/bin/composer.phar"
Step 6 : Close your terminal and reopen your terminal and run bellow command composer
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
@foreach($datas as $student)
{{$student}}
@endforeach
[Link here]
It seems like the database size limitation has been increased to 10GB.. good new
To create not optional data I recommend using it:
let key = "1234567"
let keyData = Data(key.utf8)
In Powershell, you'll need to import the active directory module, then use the get-adgroupmember, and then measure-object. For example, to get the number of users belonging to the group "domain users", do the following:
Import-Module activedirecotry
Get-ADGroupMember "domain users" | Measure-Object
When entering the group name after "Get-ADGroupMember", if the name is a single string with no spaces, then no quotes are necessary. If the group name has spaces in it, use the quotes around it.
The output will look something like:
Count : 12345
Average :
Sum :
Maximum :
Minimum :
Property :
Note - importing the active directory module may be redundant if you're already using PowerShell for other AD admin tasks.
Use Case:
With “And” the compiler will check all conditions so if you are checking that an object could be “Nothing” and then you are checking one of it’s properties you will have a run time error.
But with AndAlso with the first “false” in the conditions it will checking the next one so you will not have an error.
Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
We use this on our website
Its a very customizable to display PDF's directly in your browser. It basically hosts the PDF in a flash object if you are not opposed to that sort of thing.
Here is a sample from our corporate website.
My approach:
I first subclass UITextField and add an indexPath property. In the cellFor... Method i hand over the indexPath property.
Then I add following code:
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:textField.indexPath];
CGPoint cellPoint = [cell convertPoint:textField.center toView:self.tableView];
[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, cellPoint.y-50);}];
to the textFieldShould/WillBegin...etc.
When the Keyboard disappears you have to reverse it with:
[UIView animateWithDuration:0.3 animations:^(void){self.tableView.contentOffset = CGPointMake(0, 0);}];
I searched and found the solution in the following URL is better.
http://www.tutorialrepublic.com/faq/call-a-function-after-some-time-in-jquery.php
It worth to try.
It adds your given function to the queue of functions to be executed on the matched element which is currently this.
$(this).delay(1000).queue(function() {
// your Code | Function here
$(this).dequeue();
});
and then execute the next function on the queue for the matched element(s) which is currently this again.
Take a look at the command
We command the jQuery engine to add a function in internal queue and then after a specific amount of time we command it to call that function, BUT so far we never told it to dequeue it from engine. Right?! And then after every thing is done we are dequeue it from jQuery engine manually. I hope the explanation could help.
Use "
instead of "
to escape it.
web.config is an XML file so you should use XML escaping.
connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word"
See this forum thread.
Update:
"
should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \"
and ""
?
Update 2:
Try single quotes for the connectionString:
connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'
Or:
connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'
Update 3:
From MSDN (SqlConnection.ConnectionString Property):
To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.
So:
connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass"word'"
The issue is not with web.config, but the format of the connection string. In a connection string, if you have a "
in a value (of the key-value pair), you need to enclose the value in '
. So, while Password=somepass"word
does not work, Password='somepass"word'
does.
$('.login').toggle(
function(){
$('#panel').animate({
height: "150",
padding:"20px 0",
backgroundColor:'#000000',
opacity:.8
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
},
function(){
$('#panel').animate({
height: "0",
padding:"0px 0",
opacity:.2
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
});
If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want
SELECT COALESCE(MAX(id)+1, 0) FROM words
I think you declared the Equals
method like this:
public override bool Equals(BOX obj)
Since the object.Equals
method takes an object, there is no method to override with this signature. You have to override it like this:
public override bool Equals(object obj)
If you want type-safe Equals,
you can implement IEquatable<BOX>
.
<input type="text" name="whatever" id="funkystyling" />
Here's the CSS for the image on the left:
#funkystyling {
background: white url(/path/to/icon.png) left no-repeat;
padding-left: 17px;
}
And here's the CSS for the image on the right:
#funkystyling {
background: white url(/path/to/icon.png) right no-repeat;
padding-right: 17px;
}
Sorting stability means that records with the same key retain their relative order before and after the sort.
So stability matters if, and only if, the problem you're solving requires retention of that relative order.
If you don't need stability, you can use a fast, memory-sipping algorithm from a library, like heapsort or quicksort, and forget about it.
If you need stability, it's more complicated. Stable algorithms have higher big-O CPU and/or memory usage than unstable algorithms. So when you have a large data set, you have to pick between beating up the CPU or the memory. If you're constrained on both CPU and memory, you have a problem. A good compromise stable algorithm is a binary tree sort; the Wikipedia article has a pathetically easy C++ implementation based on the STL.
You can make an unstable algorithm into a stable one by adding the original record number as the last-place key for each record.
If you have access to python
, this is a helper that will get the yyyy-mm-dd
date value for any arbitrary n
days ago:
function get_n_days_ago {
local days=$1
python -c "import datetime; print (datetime.date.today() - datetime.timedelta(${days})).isoformat()"
}
# today is 2014-08-24
$ get_n_days_ago 1
2014-08-23
$ get_n_days_ago 2
2014-08-22
This how I do it in V3:
I start by loading the google maps api and within the callback method initialize()
I load MarkerWithLabel.js that I found here:
function initialize() {
$.getScript("/js/site/marker/MarkerWithLabel.js#{applicationBean.version}", function(){
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(currentLat, currentLng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('mapholder'),
mapOptions);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < mapData.length; i++) {
createMarker(i+1, map, mapData[i]); <!-- MARKERS! -->
extendBounds(bounds, mapData[i]);
}
map.fitBounds(bounds);
var maximumZoomLevel = 16;
var minimumZoomLevel = 11;
var ourZoom = defaultZoomLevel; // default zoom level
var blistener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
if (this.getZoom(map.getBounds) > 16) {
this.setZoom(maximumZoomLevel);
}
google.maps.event.removeListener(blistener);
});
});
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
I then create the markers with createMarker()
:
function createMarker(number, currentMap, currentMapData) {
var marker = new MarkerWithLabel({
position: new google.maps.LatLng(currentMapData[0], currentMapData[1]),
map: currentMap,
icon: '/img/sticker/empty.png',
shadow: '/img/sticker/bubble_shadow.png',
transparent: '/img/sticker/bubble_transparent.png',
draggable: false,
raiseOnDrag: false,
labelContent: ""+number,
labelAnchor: new google.maps.Point(3, 30),
labelClass: "mapIconLabel", // the CSS class for the label
labelInBackground: false
});
}
Since I added mapIconLabel class to the marker I can add some css rules in my css:
.mapIconLabel {
font-size: 15px;
font-weight: bold;
color: #FFFFFF;
font-family: 'DINNextRoundedLTProMediumRegular';
}
And here is the result:
The first problem with your script is that you have to put a space after the [
.
Type type [
to see what is really happening. It should tell you that [
is an alias to test
command, so [ ]
in bash is not some special syntax for conditionals, it is just a command on its own. What you should prefer in bash is [[ ]]
. This common pitfall is greatly explained here and here.
Another problem is that you didn't quote "$f"
which might become a problem later. This is explained here
You can use arithmetic expressions in if
, so you don't have to use [ ]
or [[ ]]
at all in some cases. More info here
Also there's no need to use \n
in every echo
, because echo
places newlines by default. If you want TWO newlines to appear, then use echo -e 'start\n'
or echo $'start\n'
. This $''
syntax is explained here
To make it completely perfect you should place --
before arbitrary filenames, otherwise rm
might treat it as a parameter if the file name starts with dashes. This is explained here.
So here's your script:
#!/bin/bash
echo "start"
for f in *.jpg
do
fname="${f##*/}"
echo "fname is $fname"
if (( fname % 2 == 1 )); then
echo "removing $fname"
rm -- "$f"
fi
done
If you are using Swift, this will do the same:
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
Hope that helps!
jQuery is still popular, but if you want to have no dependencies, see below. Short & clear function to find out if radio button is checked on ES-2015:
function getValueFromRadioButton( name ){_x000D_
return [...document.getElementsByName(name)]_x000D_
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)_x000D_
}_x000D_
_x000D_
console.log( getValueFromRadioButton('payment') );
_x000D_
<div> _x000D_
<input type="radio" name="payment" value="offline">_x000D_
<input type="radio" name="payment" value="online">_x000D_
<input type="radio" name="payment" value="part" checked>_x000D_
<input type="radio" name="payment" value="free">_x000D_
</div>
_x000D_
One checkbox to rule them all
For people still looking for plugin to control checkboxes through one that's lightweight, has out-of-the-box support for UniformJS and iCheck and gets unchecked when at least one of controlled checkboxes is unchecked (and gets checked when all controlled checkboxes are checked of course) I've created a jQuery checkAll plugin.
Feel free to check the examples on documentation page.
For this question example all you need to do is:
$( "#checkAll" ).checkall({
target: "input:checkbox"
});
Isn't that clear and simple?
**Filter by name, age ** also, you can use the map function
difference between map and filter
1. map - The map() method creates a new array with the results of calling a function for every array element. The map method allows items in an array to be manipulated to the user’s preference, returning the conclusion of the chosen manipulation in an entirely new array. For example, consider the following array:
2. filter - The filter() method creates an array filled with all array elements that pass a test implemented by the provided function. The filter method is well suited for particular instances where the user must identify certain items in an array that share a common characteristic. For example, consider the following array:
const users = [
{ name: "john", age: 23 },
{ name: "john", age:43 },
{ name: "jim", age: 101 },
{ name: "bob", age: 67 }
];
const user = _.filter(users, {name: 'jim', age: 101});
console.log(user);
Try this:
SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)
Suggest replacing this:
char str[1024];
char tmp = '.';
strcat(str, tmp);
with this:
char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()
strcat(str, tmp); //
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
Here's my current implementation:
$.liveClickHold = function(selector, fn) {
$(selector).live("mousedown", function(evt) {
var $this = $(this).data("mousedown", true);
setTimeout(function() {
if ($this.data("mousedown") === true) {
fn(evt);
}
}, 500);
});
$(selector).live("mouseup", function(evt) {
$(this).data("mousedown", false);
});
}
public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;
public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}
public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}
Persistance
public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_CreateEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);
try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
Repository
Task<ResponseStatusViewModel> Create(EmployeeModel Employee);
public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}
private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}
from itertools import repeat, starmap
results = list(starmap(do, repeat((), 3)))
See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:
for _ in starmap(do, repeat((), 3)): pass
but that's getting ugly.
The net/http api can be tough to use.
require "net/http"
uri = URI.parse(uri)
Net::HTTP.new(uri.host, uri.port).start do |client|
request = Net::HTTP::Post.new(uri.path)
request.body = "{}"
request["Content-Type"] = "application/json"
client.request(request)
end
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
Here we can use below query to the first date of the month and last date of the month.
SELECT DATEADD(DAY,1,EOMONTH(Getdate(),-1)) as 'FD',Cast(Getdate()-1 as Date)
as 'LD'
There was an error in understanding of return Type Just add Header and it will solve your problem
@Headers("Content-Type: application/json")
This version should work:
DELETE WorkRecord2
FROM WorkRecord2
INNER JOIN Employee ON EmployeeRun=EmployeeNo
Where Company = '1' AND Date = '2013-05-06'
This answer is rather late given the question date, but someone may find it useful.
None of the above solutions worked for me in Visual Studio 2012 on a local project, Net Framework 4.5 MVC 4. For context, I was following a tutorial on creating a barebones Web Api on CodeProject (http://www.codeproject.com/Articles/615805/Creating-a-Clean-Minimal-Footprint-ASP-NET-WebAPI) when I ran into this problem.
What did work for me was explicitly adding "System.Web.Mvc" to my application's references, even though the application already did reference "System.Web".
In an elevated Command Prompt write this :
To disable:
bcdedit /set hypervisorlaunchtype off
To enable:
bcdedit /set hypervisorlaunchtype auto
(From comments - restart to take effect)
If you want better performance you can use this version.
public const long UnixEpochTicks = 621355968000000000;
public const long TicksPerMillisecond = 10000;
public const long TicksPerSecond = TicksPerMillisecond * 1000;
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DateTime FromUnixTimestamp(this long unixTime)
{
return new DateTime(UnixEpochTicks + unixTime * TicksPerSecond);
}
From a quick benchmark (BenchmarkDotNet) under net471 I get this number:
Method | Mean | Error | StdDev | Scaled |
-------------- |---------:|----------:|----------:|-------:|
LukeH | 5.897 ns | 0.0897 ns | 0.0795 ns | 1.00 |
MyCustom | 3.176 ns | 0.0573 ns | 0.0536 ns | 0.54 |
2x faster against LukeH's version (if the performance mater)
This is similar to how DateTime internally work.
In java.util.timer one can use .cancel()
to stop the timer and clear all pending tasks.
The thing here is that you're using a for loop outside of your conditional statement.
After the conditions in your IF statement are met you probably navigate to another page, thus when the for loop attempts to iterate once more, you get the stale element error because you're on a different page.
You can add a break at the end of your if statement, this worked for me.
You don't need to use textarea#message
var message = $('textarea#message').val();
You can directly use
var message = $('#message').val();
You have to add Imports System.Runtime.InteropServices
to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
Fiddle: http://jsfiddle.net/33HMj/
Js:
var md5 = function(value) {
return CryptoJS.MD5(value).toString();
}
$("input").keyup(function () {
var value = $(this).val(),
hash = md5(value);
$(".test").html(hash);
});
easy_install BeautifulSoup4
or
easy_install BeautifulSoup
to install easy_install
http://pypi.python.org/pypi/setuptools#files
I needed to see the results of this script and was able to do so by incorporating the below:
var i=0;
function increase()
{
i++;
document.getElementById('boldstuff').innerHTML= +i;
}
<p>var = <b id="boldstuff">0</b></p>
<input type="button" onclick="increase();">
add the "script" tag above all and a closing script tag below the function end curly brace. Returning false caused firefox to hang when I tried it. All other solutions didn't show the result of the increment, in my experience.
My usual trick is to simply print sys.path
in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve
. Then check dirs & files in the places that path shows..
You do that by first having:
import sys
and in python 2 with print expression:
print sys.path
or in python 3 with the print function:
print(sys.path)
Does this work without alternation?
^((part)1(, \22)?)?(part2)?$
or why not this?
^((part)1(, (\22))?)?(\4)?$
The first works for all conditions the second for all but part2
(using GNU sed 4.1.5)
if you are using same date format and have select query where date in oracle :
select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';
To_DATE provided by oracle
What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.
You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.
Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).
Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org
Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.
In summary then: it all depends on your region.
Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.
Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.
As you use Joda Time, you should use DateTimeFormatter
:
final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);
If using Java 8 or later, then refer to hertzi's answer
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3