You could check if a function specific to the Date object exists:
function getFormatedDate(date) {
if (date.getMonth) {
var month = date.getMonth();
}
}
This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.
In my case this was caused by an integer overflow. I had a UInt16, and was doubling the value to put into an Int. The faulty code was
let result = Int(myUInt16 * 2)
However, this multiplies as a UInt16, then converts to Int. So if myUInt16 contains a value over 32767 then an overflow occurs.
All was well once I corrected the code to
let result = Int(myUint16) * 2
toDataURL gives you a string and you can put that string to a hidden input.
If your project is not AndroidX (mean Appcompat) and got this error, try to downgrade dependencies versions that triggers this error, in my case play-services-location ("implementation 'com.google.android.gms:play-services-location:17.0.0'") , I solved the problem by downgrading to com.google.android.gms:play-services-location:16.0.0'
If you always add to the end, then each element will be added to the end and stay that way until you change it.
If you always insert at the start, then each element will appear in the reverse order you added them.
If you insert them in the middle, the order will be something else.
(OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-)
pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)]
cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]
R = max(i for r in [random.random()] for i,c in cdf if c <= r)
I pseudo-confirmed that this works by eyeballing the output of this expression:
sorted(max(i for r in [random.random()] for i,c in cdf if c <= r)
for _ in range(1000))
I had to:
\\127.0.0.1\SSRSFileShare
sorted
return a new sorted list from the items in iterable.
CODE
import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print sorted(a)
OUTPUT
[1, 2, 3, 6, 8]
Here is an SSCCE,
package experiment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class KeyListenerTester extends JFrame implements KeyListener {
JLabel label;
public KeyListenerTester(String s) {
super(s);
JPanel p = new JPanel();
label = new JLabel("Key Listener!");
p.add(label);
add(p);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key typed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key typed");
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key pressed");
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key Released");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key Released");
}
}
public static void main(String[] args) {
new KeyListenerTester("Key Listener Tester");
}
}
Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings
You can do in this way:
Integer i = 1;
new BigInteger("" + i);
Your initial statement in the marked solution isn't entirely true. While your new solution may accomplish your original goal, it is still possible to circumvent the original error while preserving your AuthorizationHandler logic--provided you have basic authentication scheme handlers in place, even if they are functionally skeletons.
Speaking broadly, Authentication Handlers and schemes are meant to establish + validate identity, which makes them required for Authorization Handlers/policies to function--as they run on the supposition that an identity has already been established.
ASP.NET Dev Haok summarizes this best best here: "Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)." https://github.com/aspnet/Security/issues/1469
In my case, the solution I'm working on provided its own implicit concept of identity, so we had no need for authentication schemes/handlers--just header tokens for authorization. So until our identity concepts changes, our header token authorization handlers that enforce the policies can be tied to 1-to-1 scheme skeletons.
Tags on endpoints:
[Authorize(AuthenticationSchemes = "AuthenticatedUserSchemeName", Policy = "AuthorizedUserPolicyName")]
Startup.cs:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "AuthenticatedUserSchemeName";
}).AddScheme<ValidTokenAuthenticationSchemeOptions, ValidTokenAuthenticationHandler>("AuthenticatedUserSchemeName", _ => { });
services.AddAuthorization(options =>
{
options.AddPolicy("AuthorizedUserPolicyName", policy =>
{
//policy.RequireClaim(ClaimTypes.Sid,"authToken");
policy.AddAuthenticationSchemes("AuthenticatedUserSchemeName");
policy.AddRequirements(new ValidTokenAuthorizationRequirement());
});
services.AddSingleton<IAuthorizationHandler, ValidTokenAuthorizationHandler>();
Both the empty authentication handler and authorization handler are called (similar in setup to OP's respective posts) but the authorization handler still enforces our authorization policies.
The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).
There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.
See this wikipedia article on Matrix Multiplication for more information.
Use a ScaleDrawable as Abhinav suggested.
The problem is that the drawable doesn't show then - it's some sort of bug in ScaleDrawables. you'll need to change the "level" programmatically. This should work for every button:
// Fix level of existing drawables
Drawable[] drawables = myButton.getCompoundDrawables();
for (Drawable d : drawables) if (d != null && d instanceof ScaleDrawable) d.setLevel(1);
myButton.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);
select 1 from table
will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:
if exists(select 1 from table where some_column = 'some_value')
What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:
1) performance & you might retrieve more data than you actually need.
2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.
public static void main(String[] args) {
Map<Integer, Point2D.Double> map = Map.of(
1, new Point2D.Double(1, 1),
2, new Point2D.Double(2, 2),
3, new Point2D.Double(3, 3),
4, new Point2D.Double(4, 4));
map.entrySet().forEach(System.out::println);
}
Pure CSS solution:
.inputfile {_x000D_
/* visibility: hidden etc. wont work */_x000D_
width: 0.1px;_x000D_
height: 0.1px;_x000D_
opacity: 0;_x000D_
overflow: hidden;_x000D_
position: absolute;_x000D_
z-index: -1;_x000D_
}_x000D_
.inputfile:focus + label {_x000D_
/* keyboard navigation */_x000D_
outline: 1px dotted #000;_x000D_
outline: -webkit-focus-ring-color auto 5px;_x000D_
}_x000D_
.inputfile + label * {_x000D_
pointer-events: none;_x000D_
}
_x000D_
<input type="file" name="file" id="file" class="inputfile">_x000D_
<label for="file">Choose a file (Click me)</label>
_x000D_
source: http://tympanus.net/codrops
U can use javascript to achive that like this:
function loadConstants() {
this.clientContext = new SP.ClientContext.get_current();
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
//U must set a timeout to recivie the exactly user u want:
function onQuerySucceeded(sender, args) {
window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {
console.log(args.get_message());
}
//By using a proper timeout, u can get current user :
function ttt(){
var clientContext = new SP.ClientContext.get_current();
var groupCollection = clientContext.get_web().get_siteGroups();
visitorsGroup = groupCollection.getByName('OLAP Portal Members');
t=this.currentUser .get_loginName().toLowerCase();
console.log ('this.currentUser .get_loginName() : '+ t);
}
You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market
Do your absolute best to find that keystore!!
When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!
BATCH LOAD - OK, so after having my previous reply deleted for just using links I have updated with the code I managed to get working. Appreciate anyone to simplify / correct / refine / put in function etc as I'm still learning this stuff, but I got batch member list add working :)
$apikey = "whatever-us99";
$list_id = "12ab34dc56";
$email1 = "[email protected]";
$fname1 = "Jack";
$lname1 = "Black";
$email2 = "[email protected]";
$fname2 = "Jill";
$lname2 = "Hill";
$auth = base64_encode( 'user:'.$apikey );
$data1 = array(
"apikey" => $apikey,
"email_address" => $email1,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $fname1,
'LNAME' => $lname1,
)
);
$data2 = array(
"apikey" => $apikey,
"email_address" => $email2,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $fname2,
'LNAME' => $lname2,
)
);
$json_data1 = json_encode($data1);
$json_data2 = json_encode($data2);
$array = array(
"operations" => array(
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_data1
),
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_data2
)
)
);
$json_post = json_encode($array);
$ch = curl_init();
$curlopt_url = "https://us99.api.mailchimp.com/3.0/batches";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post);
print_r($json_post . "\n");
$result = curl_exec($ch);
var_dump($result . "\n");
print_r ($result . "\n");
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads
and then you can parse it with index.
Instead of using .read()
to intermediately save it to memory and then read it to json
, allow json
to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
I have had this problem frequently with multiple concurrent goroutines.
It may or may not be a good pattern, but I define a a struct for my workers with a quit channel and field for the worker state:
type Worker struct {
data chan struct
quit chan bool
stopped bool
}
Then you can have a controller call a stop function for the worker:
func (w *Worker) Stop() {
w.quit <- true
w.stopped = true
}
func (w *Worker) eventloop() {
for {
if w.Stopped {
return
}
select {
case d := <-w.data:
//DO something
if w.Stopped {
return
}
case <-w.quit:
return
}
}
}
This gives you a pretty good way to get a clean stop on your workers without anything hanging or generating errors, which is especially good when running in a container.
This will run for a lot more than hours. Assuming it loops at 1 GHz (which it won't - it will be a lot slower than that), it will run for 10790283070806014188970 years. Which is about 83 billion times longer than the age of the universe.
Assuming Moores law holds, it would be a lot quicker to not run this program, wait several hundred years and run it on a computer that is billions of times faster. In fact, any program that takes longer to run than it takes CPU speeds to double (about 18 months) will complete sooner if you wait until the CPU speeds have increased and buy a new CPU before running it (unless you write it so that it can be suspended and resumed on new hardware).
If message.value[] is string:
if message.value[0] in ('/', '\'):
do_stuff()
If it not str
You can add .a file in the linking command:
gcc yourfiles /path/to/library/libLIBRARY.a
But this is not talking with gcc driver, but with ld
linker as options like -Wl,anything
are.
When you tell gcc or ld -Ldir -lLIBRARY
, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose
). To change order of library types checked you can use -Wl,-Bstatic
and -Wl,-Bdynamic
. Here is a man page of gnu LD: http://linux.die.net/man/1/ld
To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3
Assuming that default setting of ld is to use dynamic libraries (it is on Linux).
Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80
(there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80
. Make sure that View ? Word Wrap
is selected.
To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User
and use any of the following rules:
{
// set vertical rulers in specified columns.
// Use "rulers": [80] for just one ruler
// default value is []
"rulers": [80, 100, 120],
// turn on word wrap for source and text
// default value is "auto", which means off for source and on for text
"word_wrap": true,
// set word wrapping at this column
// default value is 0, meaning wrapping occurs at window width
"wrap_width": 80
}
These settings can also be used in a .sublime-project
file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings
file if you only want them to apply to files written in a certain language (Python.sublime-settings
vs. JavaScript.sublime-settings
, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User
.
As always, if you have multiple entries in your settings file, separate them with commas ,
except for after the last one. The entire content should be enclosed in curly braces { }
. Basically, make sure it's valid JSON.
If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.
Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0
and O
(digit zero and capital letter oh) and 1
and l
(digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
It sounds like the best way is for you to iterate over entries using map.entrySet()
since map.containsValue()
probably does this anyway.
This will give you the count per month for 2012;
SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);
Demo here.
If you have a directory open in VSCode, and want to search a subdirectory, then either:
files to include
field enter the path with a leading ./
,or
Find in Folder...
option.On linux, mail utility can be used to send attachment with option "-a". Go through man pages to read about the option. For eg following code will send an attachment :
mail -s "THIS IS SUBJECT" -a attachment.txt [email protected] <<< "Hi Buddy, Please find failure reports."
Yes, it's slower.
But remember the damn #1 rule--PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL
(Well, may be tied with #1 for DRY)
I swear, if someone came up to me at work and asked me this I'd be very watchful over their code for the next few months.
You must never optimize until you are sure you need it, until then, just write good, readable code.
Oh, and I don't mean write stupid code either. Just be thinking about the cleanest way you can possibly do it--no copy and paste, etc. (Still be wary of stuff like inner loops and using the collection that best fits your need--Ignoring these isn't "unoptimized" programming, it's "bad" programming)
It freaks me out when I hear questions like this, but then I forget that everyone has to go through learning all the rules themselves before they really get it. You'll get it after you've spent a man-month debugging something someone "Optimized".
EDIT:
An interesting thing happened in this thread. Check the #1 answer, it's an example of how powerful the compiler is at optimizing things. The test is completely invalid because the non-reflective instantiation can be completely factored out.
Lesson? Don't EVER optimize until you've written a clean, neatly coded solution and proven it to be too slow.
I adopted the @Jotne solution and works perfectly! For example for mongodb server in my NAS
#! /bin/bash
case "$(pidof mongod | wc -w)" in
0) echo "Restarting mongod:"
mongod --config mongodb.conf
;;
1) echo "mongod already running"
;;
esac
In the HTML page you have to to put your css code between the tags, while in the body a div which has as id rectangle. Here the code:
<!doctype>
<html>
<head>
<style>
#rectangle
{
all your css code
}
</style>
</head>
<body>
<div id="rectangle"></div>
</body>
</html>
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
bin/hadoop fs -put /localfs/destination/path /hdfs/source/path
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
I like to use rails-settings for global configuration values that need to be changeable via web interface.
Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).
Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template
, ng-container
and ViewContainerRef
in following way:
<div>
<ng-container #outlet >
</ng-container>
</div>
<ng-template #content>
<child></child>
</ng-template>
Then in component having reference to both #outlet
and #content
we can clear outlets' content and insert another instance of child component:
@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;
private rerender() {
this.outletRef.clear();
this.outletRef.createEmbeddedView(this.contentRef);
}
Additionally initial content should be inserted on AfterContentInit
hook:
ngAfterContentInit() {
this.outletRef.createEmbeddedView(this.contentRef);
}
Full working solution can be found here https://stackblitz.com/edit/angular-component-rerender .
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
I found another working solution by Douglas.
This method removes all event handlers which are set on a specific routet event on a element.
Use it like
Remove_RoutedEventHandlers(myImage, Image.MouseLeftButtonDownEvent);
Full code:
/// <summary>
/// Removes all event handlers subscribed to the specified routed event from the specified element.
/// </summary>
/// <param name="element">The UI element on which the routed event is defined.</param>
/// <param name="RoutetEvent_ToRemove">The routed event for which to remove the event handlers.</param>
public static void RemoveRoutedEventHandlers(UIElement UIElement_Target, RoutedEvent RoutetEvent_ToRemove)
{
// Get the EventHandlersStore instance which holds event handlers for the specified element.
// The EventHandlersStore class is declared as internal.
PropertyInfo PropertyInfo_EventHandlersStore = typeof(UIElement).GetProperty(
"EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic);
object oEventHandlersStore = PropertyInfo_EventHandlersStore.GetValue(UIElement_Target, null);
// If there's no event handler subscribed, return
if (oEventHandlersStore == null) return;
// Invoke the GetRoutedEventHandlers method on the EventHandlersStore instance
// for getting an array of the subscribed event handlers.
MethodInfo MethodInfo_RoutedEventHandlers = oEventHandlersStore.GetType().GetMethod(
"GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
RoutedEventHandlerInfo[] RoutedEventHandlerInfos = (RoutedEventHandlerInfo[])MethodInfo_RoutedEventHandlers.Invoke(
oEventHandlersStore, new object[] { RoutetEvent_ToRemove });
// Iteratively remove all routed event handlers from the element.
foreach (RoutedEventHandlerInfo RoutedEventHandlerInfo_Tmp in RoutedEventHandlerInfos)
UIElement_Target.RemoveHandler(RoutetEvent_ToRemove, RoutedEventHandlerInfo_Tmp.Handler);
}
Which particular version of Ubuntu is this and is this Ubuntu Server Edition?
Recent Ubuntu Server Editions (such as 10.04) ship with AppArmor and MySQL's profile might be in enforcing mode by default. You can check this by executing sudo aa-status
like so:
# sudo aa-status
5 profiles are loaded.
5 profiles are in enforce mode.
/usr/lib/connman/scripts/dhclient-script
/sbin/dhclient3
/usr/sbin/tcpdump
/usr/lib/NetworkManager/nm-dhcp-client.action
/usr/sbin/mysqld
0 profiles are in complain mode.
1 processes have profiles defined.
1 processes are in enforce mode :
/usr/sbin/mysqld (1089)
0 processes are in complain mode.
If mysqld is included in enforce mode, then it is the one probably denying the write. Entries would also be written in /var/log/messages
when AppArmor blocks the writes/accesses. What you can do is edit /etc/apparmor.d/usr.sbin.mysqld
and add /data/
and /data/*
near the bottom like so:
...
/usr/sbin/mysqld {
...
/var/log/mysql/ r,
/var/log/mysql/* rw,
/var/run/mysqld/mysqld.pid w,
/var/run/mysqld/mysqld.sock w,
**/data/ r,
/data/* rw,**
}
And then make AppArmor reload the profiles.
# sudo /etc/init.d/apparmor reload
WARNING: the change above will allow MySQL to read and write to the /data directory. We hope you've already considered the security implications of this.
Make your local repo match the remote repo with:
git reset --hard origin/master
Then push again.
Given an answer as high voted and views. I did find the answer with mixed of here and other links.
I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)
//css
.disabled{
pointer-events:none;
opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done
So rather than write long code, I found an interesting solution via CSS.
$(document).ready(function () {_x000D_
var PatientId ; _x000D_
//var PatientId =1; //remove to test enable i.e. patient selected_x000D_
if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
console.log(PatientId);_x000D_
$("#dvHeaderSubMenu a").each(function () { _x000D_
$(this).addClass('disabled');_x000D_
}); _x000D_
return;_x000D_
}_x000D_
})
_x000D_
.disabled{_x000D_
pointer-events:none;_x000D_
opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
<ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
<li class="m-nav__item">_x000D_
<a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
Overview_x000D_
</a>_x000D_
</li>_x000D_
_x000D_
<li class="m-nav__item active">_x000D_
<a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon fa fa-user"></i>_x000D_
Personal_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
<a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
Insurance Claim_x000D_
</a>_x000D_
<div class="m-dropdown__wrapper">_x000D_
<span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
_x000D_
<ul class="m-nav">_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Primary_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-interface"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Secondary_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Medical_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
_x000D_
</li>_x000D_
</ul> _x000D_
</div>
_x000D_
Here is another (working) solution : just resize your images to the size you want :)
.pdflink:after {
display: block;
width: 20px;
height: 10px;
content:url('/images/pdf.png');
}
you need pdf.png to be 20px * 10px for this to work. The 20px/10px in the css are here to give the size of the block so that the elements that come after the block are not all messed up with the image
Don't forget to keep a copy of the raw image in its original size
Have you read this :
Delegates are a useful construct in event-based systems. Essentially Delegates are objects that encode a method dispatch on a specified object. This document shows how java inner classes provide a more generic solution to such problems.
What is a Delegate? Really it is very similar to a pointer to member function as used in C++. But a delegate contains the target object alongwith the method to be invoked. Ideally it would be nice to be able to say:
obj.registerHandler(ano.methodOne);
..and that the method methodOne would be called on ano when some specific event was received.
This is what the Delegate structure achieves.
Java Inner Classes
It has been argued that Java provides this functionality via anonymous inner classes and thus does not need the additional Delegate construct.
obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
methodOne(ev);
}
} );
At first glance this seems correct but at the same time a nuisance. Because for many event processing examples the simplicity of the Delegates syntax is very attractive.
General Handler
However, if event-based programming is used in a more pervasive manner, say, for example, as a part of a general asynchronous programming environment, there is more at stake.
In such a general situation, it is not sufficient to include only the target method and target object instance. In general there may be other parameters required, that are determined within the context when the event handler is registered.
In this more general situation, the java approach can provide a very elegant solution, particularly when combined with use of final variables:
void processState(final T1 p1, final T2 dispatch) {
final int a1 = someCalculation();
m_obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
dispatch.methodOne(a1, ev, p1);
}
} );
}
final * final * final
Got your attention?
Note that the final variables are accessible from within the anonymous class method definitions. Be sure to study this code carefully to understand the ramifications. This is potentially a very powerful technique. For example, it can be used to good effect when registering handlers in MiniDOM and in more general situations.
By contrast, the Delegate construct does not provide a solution for this more general requirement, and as such should be rejected as an idiom on which designs can be based.
You should to address Java to windows.
JAVA_HOME
, and the variable value to the address you installed Java. For example, for me it is C:\ProgramFiles\Java\jdk1.8.0_66
. After that, click the okay button.Assign your image to a string. Eg image Now set icon to a fixed size label.
image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
To add on to chepner's answer for Python 3.0 you can alternatively do:
x = lambda x: list(map(print, x))
Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.
I'll just leave this here for reference.
Go to Run type services.msc
. Check whether MySQL services is running or not. If not, start it manually. Once it started, type mysqlshow
to test the service.
-pattern_type glob
This great option makes it easier to select the images in many cases.
Slideshow video with one image per second
ffmpeg -framerate 1 -pattern_type glob -i '*.png' \
-c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Add some music to it, cutoff when the presumably longer audio when the images end:
ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
-c:a copy -shortest -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Here are two demos on YouTube:
Be a hippie and use the Theora patent-unencumbered video format:
ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
-c:a copy -shortest -c:v libtheora -r 30 -pix_fmt yuv420p out.ogg
Your images should of course be sorted alphabetically, typically as:
0001-first-thing.jpg
0002-second-thing.jpg
0003-and-third.jpg
and so on.
I would also first ensure that all images to be used have the same aspect ratio, possibly by cropping them with imagemagick
or nomacs beforehand, so that ffmpeg will not have to make hard decisions. In particular, the width has to be divisible by 2, otherwise conversion fails with: "width not divisible by 2".
Normal speed video with one image per frame at 30 FPS
ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
-c:v libx264 -pix_fmt yuv420p out.mp4
Here's what it looks like:
GIF generated with: https://askubuntu.com/questions/648603/how-to-create-an-animated-gif-from-mp4-video-via-command-line/837574#837574
Add some audio to it:
ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
-i audio.ogg -c:a copy -shortest -c:v libx264 -pix_fmt yuv420p out.mp4
Result: https://www.youtube.com/watch?v=HG7c7lldhM4
These are the test media I've used:a
wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true
unzip opengl-rotating-triangle.zip
cd opengl-rotating-triangle
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
Images generated with: How to use GLUT/OpenGL to render to a file?
It is cool to observe how much the video compresses the image sequence way better than ZIP as it is able to compress across frames with specialized algorithms:
opengl-rotating-triangle.mp4
: 340K opengl-rotating-triangle.zip
: 7.3M Convert one music file to a video with a fixed image for YouTube upload
Answered at: https://superuser.com/questions/700419/how-to-convert-mp3-to-youtube-allowed-video-format/1472572#1472572
Full realistic slideshow case study setup step by step
There's a bit more to creating slideshows than running a single ffmpeg command, so here goes a more interesting detailed example inspired by this timeline.
Get the input media:
mkdir -p orig
cd orig
wget -O 1.png https://upload.wikimedia.org/wikipedia/commons/2/22/Australopithecus_afarensis.png
wget -O 2.jpg https://upload.wikimedia.org/wikipedia/commons/6/61/Homo_habilis-2.JPG
wget -O 3.jpg https://upload.wikimedia.org/wikipedia/commons/c/cb/Homo_erectus_new.JPG
wget -O 4.png https://upload.wikimedia.org/wikipedia/commons/1/1f/Homo_heidelbergensis_-_forensic_facial_reconstruction-crop.png
wget -O 5.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Sabaa_Nissan_Militiaman.jpg/450px-Sabaa_Nissan_Militiaman.jpg
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
cd ..
# Convert all to PNG for consistency.
# https://unix.stackexchange.com/questions/29869/converting-multiple-image-files-from-jpeg-to-pdf-format
# Hardlink the ones that are already PNG.
mkdir -p png
mogrify -format png -path png orig/*.jpg
ln -P orig/*.png png
Now we have a quick look at all image sizes to decide on the final aspect ratio:
identify png/*
which outputs:
png/1.png PNG 557x495 557x495+0+0 8-bit sRGB 653KB 0.000u 0:00.000
png/2.png PNG 664x800 664x800+0+0 8-bit sRGB 853KB 0.000u 0:00.000
png/3.png PNG 544x680 544x680+0+0 8-bit sRGB 442KB 0.000u 0:00.000
png/4.png PNG 207x238 207x238+0+0 8-bit sRGB 76.8KB 0.000u 0:00.000
png/5.png PNG 450x600 450x600+0+0 8-bit sRGB 627KB 0.000u 0:00.000
so the classic 480p (640x480 == 4/3) aspect ratio seems appropriate.
Do one conversion with minimal resizing to make widths even (TODO
automate for any width, here I just manually looked at identify
output and reduced width and height by one):
mkdir -p raw
convert png/1.png -resize 556x494 raw/1.png
ln -P png/2.png png/3.png png/4.png png/5.png raw
ffmpeg -framerate 1 -pattern_type glob -i 'raw/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p raw.mp4
This produces terrible output, because as seen from:
ffprobe raw.mp4
ffmpeg just takes the size of the first image, 556x494, and then converts all others to that exact size, breaking their aspect ratio.
Now let's convert the images to the target 480p aspect ratio automatically by cropping as per ImageMagick: how to minimally crop an image to a certain aspect ratio?
mkdir -p auto
mogrify -path auto -geometry 640x480^ -gravity center -crop 640x480+0+0 png/*.png
ffmpeg -framerate 1 -pattern_type glob -i 'auto/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p auto.mp4
So now, the aspect ratio is good, but inevitably some cropping had to be done, which kind of cut up interesting parts of the images.
The other option is to pad with black background to have the same aspect ratio as shown at: Resize to fit in a box and set background to black on "empty" part
mkdir -p black
ffmpeg -framerate 1 -pattern_type glob -i 'black/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p black.mp4
Generally speaking though, you will ideally be able to select images with the same or similar aspect ratios to avoid those problems in the first place.
About the CLI options
Note however that despite the name, -glob
this is not as general as shell Glob patters, e.g.: -i '*'
fails: https://trac.ffmpeg.org/ticket/3620 (apparently because filetype is deduced from extension).
-r 30
makes the -framerate 1
video 30 FPS to overcome bugs in players like VLC for low framerates: VLC freezes for low 1 FPS video created from images with ffmpeg Therefore it repeats each frame 30 times to keep the desired 1 image per second effect.
Next steps
You will also want to:
cut up the part of the audio that you want before joining it: Cutting the videos based on start and end time using ffmpeg
ffmpeg -i in.mp3 -ss 03:10 -to 03:30 -c copy out.mp3
TODO: learn to cut and concatenate multiple audio files into the video without intermediate files, I'm pretty sure it's possible:
Tested on
ffmpeg 3.4.4, vlc 3.0.3, Ubuntu 18.04.
Bibliography
There's better support for this now through conda-env
. You can, for example, now do:
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"
It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml
file.
If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml
), then run the command: conda env update -f environment.yml
.
It's more likely that you would want to create a new environment:
conda env create -f environment.yml
(changed as supposed in the comments)
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
If you have node
then you can use fs
like in this answer to get all the files:
const { resolve } = require('path'),
{ readdir } = require('fs').promises;
async function getFiles(dir) {
const dirents = await readdir(dir, { withFileTypes: true });
const files = await Promise.all(dirents.map((dirent) => {
const res = resolve(dir, dirent.name);
return dirent.isDirectory() ? getFiles(res) : res;
}));
return Array.prototype.concat(...files);
}
And you might use that like this:
const directory = "./Documents/";
getFiles(directory).then(results => {
const html = `<ul>` +
results.map(fileOrDirectory => `<li>${fileOrDirectory}</li>`).join('\n') +
`</ul>`;
process.stdout.write(html);
// or you could use something like fs.writeFile to write the file directly
});
You could call it at the command-line with something like this:
$ node thatScript.js > index.html
You just need to escape the quote in your first example:
$ sed 's/\"//g' file.txt
If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.
TaskCompletionSource<bool> tcs = null;
private async void Button_Click(object sender, RoutedEventArgs e)
{
tcs = new TaskCompletionSource<bool>();
await tcs.Task;
WelcomeTitle.Text = "Finished work";
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
tcs?.TrySetResult(true);
}
This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change
await tcs.Task;
to
await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
WelcomeTitle.Text = "Task Completed";
else
WelcomeTitle.Text = "Task Timed Out";
Because of the way the function is called (i.e. as a simple call to a function variable), this
is the global object (for which window
is an alias in browsers). Use the obj
parameter instead.
Also, creating a jQuery object and the using its attr()
method for obtaining an element ID is inefficient and unnecessary. Just use the element's id
property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
The problem with __FILE__
is that it will print the core module ".pm" path not necessarily the ".cgi" or ".pl" script path that is running. I guess it depends on what your goal is.
It seems to me that Cwd
just needs to be updated for mod_perl. Here is my suggestion:
my $path;
use File::Basename;
my $file = basename($ENV{SCRIPT_NAME});
if (exists $ENV{MOD_PERL} && ($ENV{MOD_PERL_API_VERSION} < 2)) {
if ($^O =~/Win/) {
$path = `echo %cd%`;
chop $path;
$path =~ s!\\!/!g;
$path .= $ENV{SCRIPT_NAME};
}
else {
$path = `pwd`;
$path .= "/$file";
}
# add support for other operating systems
}
else {
require Cwd;
$path = Cwd::getcwd()."/$file";
}
print $path;
Please add any suggestions.
This is the simple Console Application to convert List to Datatable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
namespace ConvertListToDataTable
{
public static class Program
{
public static void Main(string[] args)
{
List<MyObject> list = new List<MyObject>();
for (int i = 0; i < 5; i++)
{
list.Add(new MyObject { Sno = i, Name = i.ToString() + "-KarthiK", Dat = DateTime.Now.AddSeconds(i) });
}
DataTable dt = ConvertListToDataTable(list);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine();
for (int x = 0; x < dt.Columns.Count; x++)
{
Console.Write(row[x].ToString() + " ");
}
}
Console.ReadLine();
}
public class MyObject
{
public int Sno { get; set; }
public string Name { get; set; }
public DateTime Dat { get; set; }
}
public static DataTable ConvertListToDataTable<T>(this List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor propertyDescriptor = props[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[props.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
}
here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.
http://jsfiddle.net/tZPg4/9397/
stack overflow requires I include some code with a jsFiddle link so please ignore snippet:
localStorage.setItem(...)
The idea of a foreign key is based on the concept of referencing a value that already exists in the main table. That is why it is called a foreign key in the other table. This concept is called referential integrity. If a foreign key is declared as a null field it will violate the the very logic of referential integrity. What will it refer to? It can only refer to something that is present in the main table. Hence, I think it would be wrong to declare a foreign key field as null.
myModal1 is the id of modal
$('#myModal1').modal({ show: true });
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Use word boundaries:
/\b($word)\b/i
Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:
/(?:\W|^)(\Q$word\E)(?:\W|$)/i
You can use the below method to store the timestamp in database specific to your desired zone/zone Id.
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Calcutta")) ;
Timestamp timestamp = Timestamp.valueOf(zdt.toLocalDateTime());
A common mistake people do is use LocaleDateTime
to get the timestamp of that instant which discards any information specif to your zone even if you try to convert it later. It does not understand the Zone.
Please note Timestamp
is of the class java.sql.Timestamp
.
df = pd.DataFrame(scale.fit_transform(df.values), columns=df.columns, index=df.index)
This should work without depreciation warnings.
Most common way:
console.log(object);
However I must mention JSON.stringify
which is useful to dump variables in non-browser scripts:
console.log( JSON.stringify(object) );
The JSON.stringify
function also supports built-in prettification as pointed out by Simon Zyx.
Example:
var obj = {x: 1, y: 2, z: 3};
console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2
The above snippet will print:
{
"x": 1,
"y": 2,
"z": 3
}
On caniuse.com you can view the browsers that support natively the JSON.stringify
function: http://caniuse.com/json
You can also use the Douglas Crockford library to add JSON.stringify
support on old browsers: https://github.com/douglascrockford/JSON-js
Docs for JSON.stringify
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I hope this helps :-)
I got the same error with a class like the following StockPickBean
. Called from this code:
List<StockPickBean> beansListcatMap.getValue();
beansList.sort(StockPickBean.Comparators.VALUE);
public class StockPickBean implements Comparable<StockPickBean> {
private double value;
public double getValue() { return value; }
public void setValue(double value) { this.value = value; }
@Override
public int compareTo(StockPickBean view) {
return Comparators.VALUE.compare(this,view); //return
Comparators.SYMBOL.compare(this,view);
}
public static class Comparators {
public static Comparator<StockPickBean> VALUE = (val1, val2) ->
(int)
(val1.value - val2.value);
}
}
After getting the same error:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
I changed this line:
public static Comparator<StockPickBean> VALUE = (val1, val2) -> (int)
(val1.value - val2.value);
to:
public static Comparator<StockPickBean> VALUE = (StockPickBean spb1,
StockPickBean spb2) -> Double.compare(spb2.value,spb1.value);
That fixes the error.
Not necessarily the most efficient, but one of the shortest and most readable using C++:
std::to_string(num).length()
you should use []
var x = ConfigurationManager.AppSettings["APIKey"];
You should all know this is inline scripting and is not a good practice at all...with that said you should definitively use javascript or jQuery for this type of thing:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" id="myButton" value="Add"/>
</form>
</body>
</html>
JQuery
var button_my_button = "#myButton";
$(button_my_button).click(function(){
window.location.href='Students.html';
});
Javascript
//get a reference to the element
var myBtn = document.getElementById('myButton');
//add event listener
myBtn.addEventListener('click', function(event) {
window.location.href='Students.html';
});
See comments why avoid inline scripting and also why inline scripting is bad
Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.
OTHERWISE, possibly GetObject(<filename with path>)
is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.
Dim wb As Workbook
Set wb = GetObject("C:\MyData.xlsx") 'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False
If you want to read a particular sheet, need not even define a Workbook variable
Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook
This should help :-
UITableViewCell* cell = (UITableViewCell*)[sender superview];
NSIndexPath* indexPath = [myTableView indexPathForCell:cell];
Here sender is the UIButton instance that is sending the event. myTableView is the UITableView instance you're dealing with.
Just get the cell reference right and all the work is done.
You may need to remove the buttons from cell's contentView & add them directly to UITableViewCell instance as it's subview.
Or
You can formulate a tag naming scheme for different UIButtons in cell.contentView. Using this tag, later you can know the row & section information as needed.
I had a case with 3 levels a'la _MainLayout.cshtml <--- _Middle.cshtml <--- Page.cshtml. Even though doing like this:
_MainLayout.cshtml
<head>
@RenderSection("head", false)
</head>
_Middle.cshtml
@section head {
@RenderSection("head")
}
and in Page.cshtml defining
@section head {
***content***
}
I would still get the error
The following sections have been defined but have not been rendered for the layout page “~/Views/Shared/_Middle.cshtml”: "head".
Turned out, the error was for the Middle.cshtml to rely on /Views/_ViewStart.cshtml to resolve it's parent layout. The problem was resolved by defining this in Middle.cshtml explicitly:
@{
Layout = "~/Views/_Shared/_MainLayout.cshtml";
}
Can't decide whether this would be by-design or a bug in MVC 4 - anyhow, problem was solved :)
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
http://www.php.net/manual/en/function.ziparchive-addfile.php
Sample 9 patch image with shadow
After a lots of research I found an easy method.
Create a 9 patch image and apply it as button or any other view's background.
You can create a 9 patch image with shadow using this website.
Put the 9 patch image in your drawable directory and apply it as the background for the button.
mButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable.your_9_patch_image);
I had the same problem: I can't commit a lot of files at once.
The commit works by:
Running a "clean up" from Tortoise SVN
Commit each file separate. Create new root folder and commit each file or folder.
** If the error returns you should repeat action no.1-2 **
Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.
To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:
var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");
Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".
I try GET 'http://example.com/?var=value'
Important use '
add >/dev/null 2>&1
for not send email when this activate
Sorry for my English
It also means you can use reserved words as variable names
say you want a class named class, since class is a reserved word, you can instead call your class class:
IList<Student> @class = new List<Student>();
You could add
/project_root/third_party_git_repository_used_by_my_project
to
/project_root/.gitignore
that should prevent the nested repo to be included in the parent repo, and you can work with them independently.
But: If a user runs git clean -dfx in the parent repo, it will remove the ignored nested repo. Another way is to symlink the folder and ignore the symlink. If you then run git clean, the symlink is removed, but the 'nested' repo will remain intact as it really resides elsewhere.
The ToolTip is a single WinForms control that handles displaying tool tips for multiple elements on a single form.
Say your button is called MyButton.
The tooltip will automatically appear when the cursor hovers over the button, but if you need to display it programmatically, call
MyToolTip.Show("Tooltip text goes here", MyButton);
in your code to show the tooltip, and
MyToolTip.Hide(MyButton);
to make it disappear again.
How is it noone has mentioned..
document.activeElement.id
I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..
if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
// action here
}
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
I have a similar problem. I need users to submit html content to a profile page with a great WYSIWYG editor (Redactorjs!), i wrote the following function to clean the submitted html:
<?php function filterxss($str) {
//Initialize DOM:
$dom = new DOMDocument();
//Load content and add UTF8 hint:
$dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$str);
//Array holds allowed attributes and validation rules:
$check = array('src'=>'#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i','href'=>'|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i');
//Loop all elements:
foreach($dom->getElementsByTagName('*') as $node){
for($i = $node->attributes->length -1; $i >= 0; $i--){
//Get the attribute:
$attribute = $node->attributes->item($i);
//Check if attribute is allowed:
if( in_array($attribute->name,array_keys($check))) {
//Validate by regex:
if(!preg_match($check[$attribute->name],$attribute->value)) {
//No match? Remove the attribute
$node->removeAttributeNode($attribute);
}
}else{
//Not allowed? Remove the attribute:
$node->removeAttributeNode($attribute);
}
}
}
var_dump($dom->saveHTML()); } ?>
The $check array holds all the allowed attributes and validation rules. Maybe this is useful for some of you. I haven't tested is yet, so tips are welcome
FYI : How to download data in CSV from Kibana:
In Kibana--> 1. Go to 'Discover' in left side
Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )
left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable
Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv
Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV
Go to 'Management' in left side--> 'Reporting'-->download your csv
Previous examples have two main drawbacks:
Below is a solution which has not such drawbacks.
By the default, the 'popover' element is inserted immediately after the referenced-element in the DOM (then notice the referenced-element and the popover are immediate sibling elements). Thus, when the 'close' button is clicked, you can simply look for its closest 'div.popover' parent, and then look for the immediately preceding sibling element of such parent.
Just add the following code in the 'onclick' handler of the 'close button:
$(this).closest('div.popover').popover('hide');
Example:
var genericCloseBtnHtml = '<button onclick="$(this).closest(\'div.popover\').popover(\'hide\');" type="button" class="close" aria-hidden="true">×</button>';
$loginForm.popover({
placement: 'auto left',
trigger: 'manual',
html: true,
title: 'Alert' + genericCloseBtnHtml,
content: 'invalid email and/or password'
});
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
It's easier to use jquery $(parent).html(code)
instead of parent.innerHTML = code
:
var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
document.write = function(code) {
$(parent).append(code);
}
document.writeln = function(code) {
document.write(code + "<br/>");
}
$(parent).html(html);
} finally {
$(window).load(function() {
document.write = oldDocumentWrite
document.writeln = oldDocumentWriteln
})
}
This also works with scripts that use document.write
and scripts loaded via src
attribute. Unfortunately even this doesn't work with Google AdSense scripts.
clone()
creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable
?)
You may want to use Arrays.copyOf(..)
for copying arrays instead of clone()
(though cloning is fine for arrays, unlike for anything else)
If you want deep cloning, check this answer
A little example to illustrate the shallowness of clone()
even if the elements are Cloneable
:
ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
System.out.println(System.identityHashCode(array[i]));
System.out.println(System.identityHashCode(clone[i]));
System.out.println(System.identityHashCode(array[i].clone()));
System.out.println("-----");
}
Prints:
4384790
4384790
9634993
-----
1641745
1641745
11077203
-----
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
Like Other said you can use something like that:
IF NOT EXISTS (SELECT 1 FROM Table)
BEGIN
--Do Something
END
ELSE
BEGIN
--Do Another Thing
END
I think to be consistant it's nicer to use @throw with your own class that extends NSException. Then you use the same notations for try catch finally:
@try {
.....
}
@catch{
...
}
@finally{
...
}
Apple explains here how to throw and handle exceptions: Catching Exceptions Throwing Exceptions
Yo could also set labels = FALSE
inside axis(...)
and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here
To remove specific key and element from hashmap use
hashmap.remove(key)
full source code is like
import java.util.HashMap;
public class RemoveMapping {
public static void main(String a[]){
HashMap hashMap = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : "+hashMap);
hashMap.remove(3);
System.out.println("Changed HashMap : "+hashMap);
}
}
for example i tried all above for characters it fails but that worked for me >> reserved a pointer then assign values
char A[];
A = new char[]{'a', 'b', 'a', 'c', 'd', 'd', 'e', 'f', 'q', 'r'};
If you actually want arrays:
>>> from array import array
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> myarray = array('c', text)
>>> myarray
array('c', 'abc')
>>> myarray[0]
'a'
>>> myarray[1]
'b'
If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> text[0]
'a'
I had some git submodule misconfiguration. I went to repo's root and issued these commands on the directories that had .git
folders previously:
git rm --cached sub/directory/path -f
Then the directories appeared in git status
.
You may want to make a copy of your repo before trying this just in case.
The simplest code would be like, keep your properties files into resources folder, either in src/main/resource or in src/test/resource. Then use below code to read properties files:
public class Utilities {
static {
rb1 = ResourceBundle.getBundle("fileNameWithoutExtension");
// do not use .properties extension
}
public static String getConfigProperties(String keyString) {
return rb1.getString(keyString);
}
}
Math.Floor()
rounds toward negative infinity
Math.Truncate
rounds up or down towards zero.
For example:
Math.Floor(-3.4) = -4
Math.Truncate(-3.4) = -3
while
Math.Floor(3.4) = 3
Math.Truncate(3.4) = 3
Similar Question Here
Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.
The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.
The simplest way is using HTML META tag like this:
<meta http-equiv="refresh" content="3;url=http://example.com/" />
Several options, by order of most appropriate way:
System.Environment.Exit
(not portable! see below)Edited 9/2013 to improve readability
Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int
return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.
Another point against using Evironment.Exit
- even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit
irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit
does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.
Consider my code:
import os
def readFile(filename):
filehandle = open(filename)
print filehandle.read()
filehandle.close()
fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir
#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)
#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)
#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)
#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)
I needed to get the form data as some sort of object. I used this:
$('#preview_form').serializeArray().reduce((function(acc, val) {
acc[val.name.replace('[', '_').replace(']', '')] = val.value;
return acc;
}), {});
Try this:
Select Project_Name, ReleaseDate, TaskName
From DB_Table
Where Project_Name like '{?Pm-?Proj_Name}'
And ReleaseDate >= currentdate
currentdate should be a valid database function or field to work. If you are using MS SQL Server, use GETDATE() instead.
If all you want is to filter records in a subreport based on a parameter from the main report, it might be easier to simply add the table to the subreport, and then create a Project_Name link between the main report and subreport. You can then use the Select Expert to filter the ReleaseDate as well.
Another alternative solution, that is recommended in the github help pages:
pbcopy < ~/.ssh/id_rsa.pub
Should this fail, I recommend using their docs to trouble shoot or generate a new key - if not already done.
Given that the value is in $value:
To echo it:
printf("%08d", $value);
To get it:
$formatted_value = sprintf("%08d", $value);
That should do the trick
This is how I did it with Kotlin to show progress with percentage.
My fragment layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/progressBar"/>
</FrameLayout>
My kotlin fragment in onViewCreated
progressBar.max = 100;
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress;
}
}
webView!!.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
progressBar.visibility = View.VISIBLE
progressBar.progress = 0;
super.onPageStarted(view, url, favicon)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view?.loadUrl(request?.url.toString())
}
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
progressBar.visibility = View.GONE
}
}
webView.loadUrl(url)
You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.
Another might be using CDATA
tags.
Example using CDATA
:
<xml>
<title>Your HTML title</title>
<htmlData><![CDATA[<html>
<head>
<script/>
</head>
<body>
Your HTML's body
</body>
</html>
]]>
</htmlData>
</xml>
Please note:
CDATA's opening character sequence: <![CDATA[
CDATA's closing character sequence: ]]>
In the converter of the chosen solution, you should add values.Clone() otherwise the parameters in the command end null
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
...
}
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
When converting SVG to transparent PNG, don't forget to put this BEFORE $imagick->readImageBlob()
:
$imagick->setBackgroundColor(new ImagickPixel('transparent'));
for me following line is working for me , I put it in the css of my body ( where image is in same folder in which my css and .html files ) :
background: url('test.jpg');
Other thing that you must care about is , be careful about image extension , be sure that your image has .jpeg or .jpg extension. Thanks
For those like me who come to this page with this problem after updating Xcode but don't have an issue with the location setting, restarting my computer did the trick.
<div id="uploadButton">UPLOAD</div>
<form action="[FILE_HANDLER_URL]" style="display:none">
<input id="myInput" type="file" />
</form>
<script>
const uploadButton = document.getElementById('uploadButton');
const myInput = document.getElementById('myInput');
uploadButton.addEventListener('click', () => {
myInput.click();
});
</script>
LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip
For me, the only thing that worked in Java 7 on OS X 10.9 was this:
// driver = new RemoteWebDriver(new URL(grid), capability);
driver.manage().window().setPosition(new Point(0,0));
driver.manage().window().setSize(new Dimension(1024,768));
Where 1024
is the width, and 768
is the height.
This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.
As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:
git checkout -b branch_name
git add <files>
git commit -m "message"
If you get the error:
error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches
Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:
git stash
git checkout -b branch_name
git stash pop
It will be as if you had made those changes after creating the new branch. Then you can commit as usual:
git add <files>
git commit -m "message"
See the answer by Carl Norum with cherry-picking, which is the right tool in this case:
git checkout <target name>
git cherry-pick <original branch>
See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:
git branch -f <original branch> <earlier commit id>
If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.
We can pretend they are filenames and remove extensions:
tools::file_path_sans_ext(a)
# [1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
If you don't use Java 8 and you don't want to use a explicit loop for some reason, try MapUtils.populateMap
from Apache Commons.
Say you have a list of Pair
s.
List<ImmutablePair<String, String>> pairs = ImmutableList.of(
new ImmutablePair<>("A", "aaa"),
new ImmutablePair<>("B", "bbb")
);
And you now want a Map of the Pair
's key to the Pair
object.
Map<String, Pair<String, String>> map = new HashMap<>();
MapUtils.populateMap(map, pairs, new Transformer<Pair<String, String>, String>() {
@Override
public String transform(Pair<String, String> input) {
return input.getKey();
}
});
System.out.println(map);
gives output:
{A=(A,aaa), B=(B,bbb)}
That being said, a for
loop is maybe easier to understand. (This below gives the same output):
Map<String, Pair<String, String>> map = new HashMap<>();
for (Pair<String, String> pair : pairs) {
map.put(pair.getKey(), pair);
}
System.out.println(map);
Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity
to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.
If you are doing automatic testing (in which you also create users) this might be a probable scenario.
In this case you need to revert to queries like:
SELECT pg_terminate_backend(procpid)
FROM pg_stat_get_activity(NULL::integer)
WHERE datid=(SELECT oid from pg_database where datname = 'your_database');
NOTE: In 9.2+ you'll have change procpid
to pid
.
To change Python 3.6.8 as the default in Ubuntu 18.04 from Python 2.7 you can try the command line tool update-alternatives
.
sudo update-alternatives --config python
If you get the error "no alternatives for python" then set up an alternative yourself with the following command:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2
Change the path /usr/bin/python3
to your desired python version accordingly.
The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.6.8
and as a result the /usr/bin/python3.6.8
was set as default python version automatically by update-alternatives command.
we can anytime switch between the above listed python alternative versions using below command and entering a selection number:
update-alternatives --config python
Important behavior changes between old and new style classes
Exception
(example below)__slots__
addedIt was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).
The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance.
Classic classes do a depth-first search from left to right. Stop on the first match. They do not have the __mro__
attribute.
class C: i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 0
assert C21().i == 2
try:
C12.__mro__
except AttributeError:
pass
else:
assert False
New-style classes MRO is more complicated to synthesize in a single English sentence. It is explained in detail here. One of its properties is that a base class is only searched for once all its derived classes have been. They have the __mro__
attribute which shows the search order.
class C(object): i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 2
assert C21().i == 2
assert C12.__mro__ == (C12, C1, C2, C, object)
assert C21.__mro__ == (C21, C2, C1, C, object)
Exception
Around Python 2.5 many classes could be raised, and around Python 2.6 this was removed. On Python 2.7.3:
# OK, old:
class Old: pass
try:
raise Old()
except Old:
pass
else:
assert False
# TypeError, new not derived from `Exception`.
class New(object): pass
try:
raise New()
except TypeError:
pass
else:
assert False
# OK, derived from `Exception`.
class New(Exception): pass
try:
raise New()
except New:
pass
else:
assert False
# `'str'` is a new style object, so you can't raise it:
try:
raise 'str'
except TypeError:
pass
else:
assert False
I think it is the best answer:
public static double StringToDouble(string toDouble)
{
toDouble = toDouble.Replace(",", "."); //Replace every comma with dot
//Count dots in toDouble, and if there is more than one dot, throw an exception.
//Value such as "123.123.123" can't be converted to double
int dotCount = 0;
foreach (char c in toDouble) if (c == '.') dotCount++; //Increments dotCount for each dot in toDouble
if (dotCount > 1) throw new Exception(); //If in toDouble is more than one dot, it means that toCount is not a double
string left = toDouble.Split('.')[0]; //Everything before the dot
string right = toDouble.Split('.')[1]; //Everything after the dot
int iLeft = int.Parse(left); //Convert strings to ints
int iRight = int.Parse(right);
//We must use Math.Pow() instead of ^
double d = iLeft + (iRight * Math.Pow(10, -(right.Length)));
return d;
}
i think you can use more than one class in a tag
for example:
<div class="whatever base"></div>
<div class="whatever2 base"></div>
so when you want to chage all div's color you can just change the .base
...i dont know how to inherit in CSS
The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values
the output is an numpy array
. So if the data has int
and float
in it then output will either have int
or float
and the columns will loose their original dtype.
Consider df
a b
0 1 4
1 2 5
2 3 6
a float64
b int64
So if you want to keep original dtype, you can do something like
row_list = df.to_csv(None, header=False, index=False).split('\n')
this will return each row as a string.
['1.0,4', '2.0,5', '3.0,6', '']
Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.
def f(row_str):
row_list = row_str.split(',')
return [float(row_list[0]), int(row_list[1])]
df_list_of_list = map(f, row_list[:-1])
[[1.0, 4], [2.0, 5], [3.0, 6]]
I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany
to look at each item in each group.
I think you just want:
List<ResultLine> result = Lines
.GroupBy(l => l.ProductCode)
.Select(cl => new ResultLine
{
ProductName = cl.First().Name,
Quantity = cl.Count().ToString(),
Price = cl.Sum(c => c.Price).ToString(),
}).ToList();
The use of First()
here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.
I'd also suggest that you should change the Quantity
and Price
properties to be int
and decimal
types respectively - why use a string property for data which is clearly not textual?
They are the same. But I suggest "while(ture)" which has best representation.
How to fix app:mergeDebugResources in Android Studio (Resource path could not resolved / R.id is not accessible)
This should resolve your Gradle issue.. good luck.
Ruby versions >= 2.4 has an Enumerable#sum method.
And to get floating point average, you can use Integer#fdiv
arr = [0,4,8,2,5,0,2,6]
arr.sum.fdiv(arr.size)
# => 3.375
For older versions:
arr.reduce(:+).fdiv(arr.size)
# => 3.375
Well, I understand this question is Visual Studio GUI related, but maybe the asker can try this trick also. Just giving a different perspective in solving this problem.
I like to use terminal a lot for GIT, so here are the simple steps:
Pre-requisites...
Now,
Don't create any file inside the repository. Keep it empty. Copy its URL. It should be something like https://github.com/Username/ProjectName.git
Open up the terminal and redirect to your Visual Studio Project directory
Configure your credentials
git config --global user.name "your_git_username"
git config --global user.email "your_git_email"
Then type these commands
git init
git add .
git commit -m "First Migration Commit"
git remote add origin paste_your_URL_here
git push -u origin master
Done...Hope this helps
One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.
Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:
p [tab][enter] Hello world!
When you type p [tab] Emmet expands it to:
<p></p>
Pressing [enter] then further expands it to:
<p>
</p>
With the cursor indented and on the line between the tags. Meaning that typing text results in:
<p>
Hello, world!
</p>
You can try like this:
private String getCharForNumber(int i) {
CharSequence css = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (i > 25) {
return null;
}
return css.charAt(i) + "";
}
Your url String needs variable markers for the map you pass to work, like:
String url = "https://app.example.com/hr/email?{email}";
Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:
String url = "https://app.example.com/hr/[email protected]";
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
Actually, it is as simple as setting major
and minor
separately:
In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]
In [10]: yscale('log')
In [11]: grid(b=True, which='major', color='b', linestyle='-')
In [12]: grid(b=True, which='minor', color='r', linestyle='--')
The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log')
, but it can also be done with plt.minorticks_on()
.
If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient()
method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:
import numpy as np
import pandas as pd
index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')
For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.
Use relative path with the pathlib
module in Python 3.4+:
from pathlib import Path
Path(__file__).parent
You can use multiple calls to parent
to go further in the path:
Path(__file__).parent.parent
As an alternative to specifying parent
twice, you can use:
Path(__file__).parents[1]
See themes on android: http://developer.android.com/guide/topics/ui/themes.html.
Under themes.xml there should be android:windowAnimationStyle
where you can see the declaration of the style in styles.xml.
Example implementation:
<style name="AppTheme" parent="...">
...
<item name="android:windowAnimationStyle">@style/WindowAnimationStyle</item>
</style>
<style name="WindowAnimationStyle">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
Updated for 2019: As previously suggested, in the latest Eclipse, go to "Install New Software" in the Help Menu and click the "add" button with this URL http://download.eclipse.org/tools/pdt/updates/latest/ that should show the latest release of PHP Development Tools (PDT). You might need to search for "php" or "pdt". For Nightly releases you can use http://download.eclipse.org/tools/pdt/updates/latest-nightly/.
You could also use the following:
<template ngFor let-item [ngForOf]="itemsList">
<div *ng-if="conditon(item)"></div>
</template>
This will only show the div if your items matches the condition
See the angular documentation for more information If you would also need the index, use the following:
<template ngFor let-item [ngForOf]="itemsList" let-i="index">
<div *ng-if="conditon(item, i)"></div>
</template>
As my purpose is to get an empty version of the test database to import data from an external previous current active source (Access database) once all is fine tuned. I found that using DBCC CloneDatabase with Verify_CloneDB option fits perfectly.
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
Here example on plain JS:
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
outline: none;_x000D_
}
_x000D_
<div _x000D_
id="myDiv"_x000D_
tabindex="0"_x000D_
>_x000D_
Press me and start typing_x000D_
</div>
_x000D_
For the updated question, you can replace what you want with something like:
someList = filter(lambda x: x not in ("a", "á", "à", "ã", "â"), someList)
filter
evaluates every element of the list by passing it to the lambda provided. In this lambda we check if the element is not one of the characters provided, because these should stay in the list.
Alternatively, if the items in someList
should be unique, you can make someList
a set and do something like this:
someList = list(set(someList)-set(("a", "á", "à", "ã", "â")))
This essentially takes the difference between the sets, which does what you want, but also makes sure every element occurs only once, which is different from a list. Note you could store someList
as a set from the beginning in this case, it will optimize things a bit.
Deleting is such a headache. I am posting the solution for Android Studio 1.0.2.
Step 1: Right click on the "Project Name" selected from the folder hierarchy like shown.
Note: It can also be deleted from the Commander View from right hand side of your window by right clicking the project name and selecting delete from the context menu.
Step 2: The project is deleted(seemingly) but gradle seems to keep the record of the project app folder(Check it by clcking on the Gradle View). Now go to File->Close Project.
Step 3: Now you are at the start window. Move the cursor on the in recent project list. Press Delete.
Step 4: Delete the folder from the explorer by moving or deleting it actually. This location is in your_user_name->Android Studio Projects->...
Step 5: Go back to the Android studio window and the project is gone for good. You can start a new project now.
How to add new line in Markdown presentation?
Check the following resource Line Return
To force a line return, place two empty spaces at the end of a line.
This, from the masters themselves (K&R, 2nd ed., pg. 106):
// strcmp: return < 0 if s < t, 0 if s == t, > 0 if s > t
int strcmp(char *s, char *t)
{
int i;
for (i = 0; s[i] == t[i]; i++)
if (s[i] == '\0')
return 0;
return s[i] - t[i];
}
My experience to the same warning message was caused by TypeError.
TypeError: invalid type comparison
So, you may want to check the data type of the Unnamed: 5
for x in df['Unnamed: 5']:
print(type(x)) # are they 'str' ?
Here is how I can replicate the warning message:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 2), columns=['num1', 'num2'])
df['num3'] = 3
df.loc[df['num3'] == '3', 'num3'] = 4 # TypeError and the Warning
df.loc[df['num3'] == 3, 'num3'] = 4 # No Error
Hope it helps.
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
I've experimented with typing "exit for" a few times and noticed it worked and VB didn't yell at me. It's an option I guess but it just looked bad.
I think the best option is similar to that shared by Tobias. Just put your code in a function and have it return when you want to break out of your loops. Looks cleaner too.
For Each item In itemlist
For Each item1 In itemlist1
If item1 = item Then
Return item1
End If
Next
Next
if you want to fill all the column:
update 'column' set 'info' where keyID!=0;
Just changed Amber's COUNT(*) to COUNT(1) for the better performance.
SELECT name, COUNT(1) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
While the GC compacts the small object heap as part of an optimization strategy to eliminate memory holes, the GC never compacts the large object heap for performance reasons**(the cost of compaction is too high for large objects (greater than 85KB in size))**. Hence if you are running a program that uses many large objects in an x86 system, you might encounter OutOfMemory exceptions. If you are running that program in an x64 system, you might have a fragmented heap.
kubectl run
= kubectl create deployment
kubectl create -f your-object-config.yaml
kubectl delete -f your-object-config.yaml
kubectl replace -f your-object-config.yaml
kubectl diff -f configs/
kubectl apply -f configs/
Just keep a currentValue variable in your controller that you update on every change. You can then compare that to the new value every time before you update it.'
The idea of using a watch is good as well, but I think a simple variable is the simplest and most logical solution.
Use the binascii
module:
>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'
See this answer: Python 3.1.1 string to hex
In "build.gradle" file, change current Kotlin version that line and press synk:
ext.kotlin_version = '1.1.1'
/// That will look like:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.1'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
/**
* @param num The number to round
* @param precision The number of decimal places to preserve
*/
function roundUp(num, precision) {
precision = Math.pow(10, precision)
return Math.ceil(num * precision) / precision
}
roundUp(192.168, 1) //=> 192.2
Copy the below code to a batch file and execute. Below requires Winzip to be installed/accessible from your machine. Do change variables as per your need.
@ECHO OFF
SET winzip_path="C:\Program Files\WinZip"
SET source_path="C:\Test"
SET output_path="C:\Output\"
SET log_file="C:\Test\unzip_log.txt"
SET file_name="*.zip"
cd %source_path%
echo Executing for %source_path% > %log_file%
FOR /f "tokens=*" %%G IN ('dir %file_name% /b') DO (
echo Processing : %%G
echo File_Name : %%G >> %log_file%
%winzip_path%\WINZIP32.EXE -e %%G %output_path%
)
PAUSE
Other answers work, but
To get the full/default price:
$product->get_price_html();
Whenever you want to use ant thread safe version of ant collection object,take help of java.util.concurrent.* package. It has almost all concurrent version of unsynchronized collection objects. eg: for ArrayList, you have java.util.concurrent.CopyOnWriteArrayList
You can do Collections.synchronizedCollection(any collection object),but remember this classical synchr. technique is expensive and comes with performence overhead. java.util.concurrent.* package is less expensive and manage the performance in better way by using mechanisms like
copy-on-write,compare-and-swap,Lock,snapshot iterators,etc.
So,Prefer something from java.util.concurrent.* package
You won't get real HTML rendering to <canvas>
per se currently, because canvas context does not have functions to render HTML elements.
There are some emulations:
html2canvas project http://html2canvas.hertzen.com/index.html (basically a HTML renderer attempt built on Javascript + canvas)
HTML to SVG to <canvas>
might be possible depending on your use case:
https://github.com/miohtama/Krusovice/blob/master/src/tools/html2svg2canvas.js
Also if you are using Firefox you can hack some extended permissions and then render a DOM window to <canvas>
After trying a few things, and coming across PyMySQL Github, this worked:
sudo pip install PyMySQL
And to import use:
import pymysql
We can a make a signed and unsigned APK file. A signed APK file can install in your device.
For creating a signed APK file:
Right-click the project in the Package Explorer
Select Android Tools -> Export Signed Application Package.
Then specify the file location for the signed .apk.
For creating an unsigned APK file:
Right-click the project in the Package Explorer
Select Android Tools -> Export Unsigned Application Package.
Then specify the file location for the unsigned APK file.
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.
HTML:
<form class="form-create-container form-create"> </form>
JS
$(document).on('submit', '.form-create', function(){
..... ..... .....
$('.form-create-container').removeClass('form-create').submit();
});
At first I was as reluctant as @fmark to switch from optparse to argparse, because:
Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html
And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)
Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.
I have found that the following works well in 2.7.x
import os
two_up = os.path.normpath(os.path.join(__file__,'../'))
I got this error in chrome when I had an unterminated string after the line that the error pointed to. After closing the string the error went away.
Example with error:
var file = files[i]; // SyntaxError: Unexpected token ILLEGAL
jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
+ "<a href=\"javascript: something('"+file.id+');\">Error is here</a>";
Example without error:
var file = files[i]; // No error
jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
+ "<a href=\"javascript: something('"+file.id+"');\">Error was here</a>";
Since PHP 7.1 there is a pseudo-type iterable
for exactly this purpose. Type-hinting iterable
accepts any array as well as any implementation of the Traversable
interface. PHP 7.1 also introduced the function is_iterable()
. For older versions, see other answers here for accomplishing the equivalent type enforcement without the newer built-in features.
Fair play: As BlackHole pointed out, this question appears to be a duplicate of Iterable objects and array type hinting? and his or her answer goes into further detail than mine.
You could write an extension method:
public static class Extension
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
I even run the command prompt as Administrator but it didn't work for me with the below error.
'keytool' is not recognized as an internal or external command,
operable program or batch file.
If the path to the keytool is not in your System paths then you will need to use the full path to use the keytool, which is
C:\Program Files\Java\jre<version>\bin
So, the command should be like
"C:\Program Files\Java\jre<version>\bin\keytool.exe" -importcert -alias certificateFileAlias -file CertificateFileName.cer -keystore cacerts
that worked for me.
you can use lambda inside map in python. wrote a gray codes generator. https://github.com/rdm750/rdm750.github.io/blob/master/python/gray_code_generator.py # your code goes here ''' the n-1 bit code, with 0 prepended to each word, followed by the n-1 bit code in reverse order, with 1 prepended to each word. '''
def graycode(n):
if n==1:
return ['0','1']
else:
nbit=map(lambda x:'0'+x,graycode(n-1))+map(lambda x:'1'+x,graycode(n-1)[::-1])
return nbit
for i in xrange(1,7):
print map(int,graycode(i))
A very simple way is to add the image as a background to a DIV then load an empty transparent gif set to the same size as the DIV in the foreground. that keeps the less determined out. They cant get the background without viewing the code and copying the URL and right clicking just downloads the transparent gif.
Query for just a single known column:
session.query(MyTable.col1).count()
No answer here, or plugin i found provided what i wanted. A minimalist method to launch my python code i wrote on Notepad++ with the press of a shortcut, with preferably no plugins.
I have Python 3.6 (64-bit), for Windows 8.1 x86_64 and Notepad++ 32bit. After you write your Python script in Notepad++ and save it, Hit F5 for Run
. Then write:
"C:\Path\to\Python\python.exe" -i "$(FULL_CURRENT_PATH)"
and hit the Run button. The i
flag forces the terminal to stay still after code execution has terminated, for you to inspect it. This command will launch the script in a cmd terminal and the terminal will still lie there, until you close it by typing exit()
.
You can save this to a shortcut for convenience (mine is CTRL + SHIFT + P).
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
Path.GetDirectoryName(@"c:\projects\roott\wsdlproj\devlop\beta2\text");
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
If you are using eclipse plugin, double click on the app-name in My Heroku Applications. In Processes tab, press Scale Button. A small window will pop-up. Increase/decrease the count and just say OK.
Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.
Note that applicable catch or finally blocks includes:
When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.
Now retrace the execution remembering that, whenever you hit throw
, you should abort tracing the current exception and start tracing the new exception.
Since Java 9 there is a method Process.getPid() which returns the native ID of a process:
public abstract class Process {
...
public long getPid();
}
To get the process ID of the current Java process one can use the ProcessHandle
interface:
System.out.println(ProcessHandle.current().pid());
I would recommend to look at the error_logs
, specifically at the upstream part where it shows specific upstream that is timing out.
Then based on that you can adjust proxy_read_timeout
, fastcgi_read_timeout
or uwsgi_read_timeout
.
Also make sure your config is loaded.
More details here Nginx upstream timed out (why and how to fix)
The simplest and also the most compact solution (for v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
Answer from here: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/
Despite the fact WordPress has been around for a while, and the method of adding scripts to themes and plugins has been the same for years, there is still some confusion around how exactly you’re supposed to add scripts. So let’s clear it up.
Since jQuery is still the most commonly used Javascript framework, let’s take a look at how you can add a simple script to your theme or plugin.
jQuery’s Compatibility Mode
Before we start attaching scripts to WordPress, let’s look at jQuery’s compatibility mode. WordPress comes pre-packaged with a copy of jQuery, which you should use with your code. When WordPress’ jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries.
What this boils down to is that you can’t use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use jQuery instead. Take a look at the code below to see what I mean:
While most answers are very cool, most of them require to have an image already sized correctly... Other solutions only work for a width and do not care of the height available, but sometimes you want to fit the content in a certain height too.
I've tried to couple them together to bring a fully portable and re-sizable solution... The trick is to use to auto scaling of an image but use an inline svg element instead of using a pre-rendered image or any form of second HTTP request...
div.holder{_x000D_
background-color:red;_x000D_
display:inline-block;_x000D_
height:100px;_x000D_
width:400px;_x000D_
}_x000D_
svg, img{_x000D_
background-color:blue;_x000D_
display:block;_x000D_
height:auto;_x000D_
width:auto;_x000D_
max-width:100%;_x000D_
max-height:100%;_x000D_
}_x000D_
.content_sizer{_x000D_
position:relative;_x000D_
display:inline-block;_x000D_
height:100%;_x000D_
}_x000D_
.content{_x000D_
position:absolute;_x000D_
top:0;_x000D_
bottom:0;_x000D_
left:0;_x000D_
right:0;_x000D_
background-color:rgba(155,255,0,0.5);_x000D_
}
_x000D_
<div class="holder">_x000D_
<div class="content_sizer">_x000D_
<svg width=10000 height=5000 />_x000D_
<div class="content">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Notice that I have used big values in the width and height attributes of the SVG, as it needs to be bigger than the maximum expected size as it can only shrink. The example makes the div's ratio 10:5
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
This is specific to Bootstrap 4.0.
HTML
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link nav-link-color" href="#about">home</a>
</li>
<li class="nav-item">
<a class="nav-link nav-link-color" href="#contact">contact</a>
</li>
</ul>
CSS
.nav-pills > li > a.active {
background-color: #ffffff !important;
color: #ffffff !important;
}
.nav-pills > li > a:hover {
color: #ffffff !important;
}
.nav-link-color {
color: #ffffff;
}