Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
If you need permissions, you cannot use 'pip' with 'sudo'. You can do a trick, so that you can use 'sudo' and install package. Just place 'sudo python -m ...' in front of your pip command.
sudo python -m pip install --user -r package_name
Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.
There are 2 steps to resolve this:
Add UseAccessibleHeader="true"
to Gridview tag:
<asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
Add the following Code to the PreRender
event:
Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
Try
MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
Catch ex As Exception
End Try
End Sub
Note setting Header Row in DataBound()
works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.
None of above answer solve my problem.
The fact is that my project did not have type script installed.
But locally I had run npm install -g typescript
. So I did not notice that typescript node dependency was not in my package json.
When I pushed it to server side, and run npm install
, then npx tsc
I get a tsc not found. In facts remote server did not have typescript installed. That was hidden because of my local global typescript install.
I found simple solution, which works fine even if you want add new fragments in the middle or replace current fragment. In my solution you should override getItemId()
which should return unique id for each fragment. Not position as by default.
There is it:
public class DynamicPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Page> mPages = new ArrayList<Page>();
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
public DynamicPagerAdapter(FragmentManager fm) {
super(fm);
}
public void replacePage(int position, Page page) {
mPages.set(position, page);
notifyDataSetChanged();
}
public void setPages(ArrayList<Page> pages) {
mPages = pages;
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
if (mPages.get(position).mPageType == PageType.FIRST) {
return FirstFragment.newInstance(mPages.get(position));
} else {
return SecondFragment.newInstance(mPages.get(position));
}
}
@Override
public int getCount() {
return mPages.size();
}
@Override
public long getItemId(int position) {
// return unique id
return mPages.get(position).getId();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
while (mFragments.size() <= position) {
mFragments.add(null);
}
mFragments.set(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mFragments.set(position, null);
}
@Override
public int getItemPosition(Object object) {
PagerFragment pagerFragment = (PagerFragment) object;
Page page = pagerFragment.getPage();
int position = mFragments.indexOf(pagerFragment);
if (page.equals(mPages.get(position))) {
return POSITION_UNCHANGED;
} else {
return POSITION_NONE;
}
}
}
Notice: In this example FirstFragment
and SecondFragment
extends abstract class PageFragment, which has method getPage()
.
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...
Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines
attribute:
- name: Generate SSH keys for vagrant user
user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
register: vagrant
- debug: var=vagrant.stdout_lines
- name: Show SSH public key
command: /bin/cat $home_directory/.ssh/id_rsa.pub
register: cat
- debug: var=cat.stdout_lines
- name: Wait for user to copy SSH public key
pause: prompt="Please add the SSH public key above to your GitHub account"
register: pause
- debug: var=pause.stdout_lines
I use automapper to copy an object. I just setup a mapping that maps one object to itself. You can wrap this operation any way you like.
According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Doing either
mystring == yourstring
or
mystring.eql? yourstring
Are equivalent.
Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience
When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.
If you want to style your site per device, you can use the user agent
value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.
You can see some standard resolutions in this link.
BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.
Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.
TIPS
Example
I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.
State of mind
Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.
Since your second question is more concrete, I'm going to address it first, and then take up your first question with the context given by the second. I wanted to give a more evidence-based answer than what's here already.
Question #2: Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?
You can answer this question for yourself by stopping your compiler before the assembler is run and looking at the asm. (Use the -S
flag if your compiler has a gcc-style interface, and -masm=intel
if you want the syntax style I'm using here.)
In any case, with modern compilers (gcc 10.2, clang 11.0) for x86-64, they only reload the variable on each loop pass if you disable optimizations. Consider the following C++ program—for intuitive mapping to asm, I'm keeping things mostly C-style and using an integer instead of a string, although the same principles apply in the string case:
#include <iostream>
static constexpr std::size_t LEN = 10;
void fill_arr(int a[LEN])
{
/* *** */
for (std::size_t i = 0; i < LEN; ++i) {
const int t = 8;
a[i] = t;
}
/* *** */
}
int main(void)
{
int a[LEN];
fill_arr(a);
for (std::size_t i = 0; i < LEN; ++i) {
std::cout << a[i] << " ";
}
std::cout << "\n";
return 0;
}
We can compare this to a version with the following difference:
/* *** */
const int t = 8;
for (std::size_t i = 0; i < LEN; ++i) {
a[i] = t;
}
/* *** */
With optimization disabled, gcc 10.2 puts 8 on the stack on every pass of the loop for the declaration-in-loop version:
mov QWORD PTR -8[rbp], 0
.L3:
cmp QWORD PTR -8[rbp], 9
ja .L4
mov DWORD PTR -12[rbp], 8 ;?
whereas it only does it once for the out-of-loop version:
mov DWORD PTR -12[rbp], 8 ;?
mov QWORD PTR -8[rbp], 0
.L3:
cmp QWORD PTR -8[rbp], 9
ja .L4
Does this make a performance impact? I didn't see an appreciable difference in runtime between them with my CPU (Intel i7-7700K) until I pushed the number of iterations into the billions, and even then the average difference was less than 0.01s. It's only a single extra operation in the loop, after all. (For a string, the difference in in-loop operations is obviously a bit greater, but not dramatically so.)
What's more, the question is largely academic, because with an optimization level of -O1
or higher gcc outputs identical asm for both source files, as does clang. So, at least for simple cases like this, it's unlikely to make any performance impact either way. Of course, in a real-world program, you should always profile rather than make assumptions.
Question #1: Is declaring a variable inside a loop a good practice or bad practice?
As with practically every question like this, it depends. If the declaration is inside a very tight loop and you're compiling without optimizations, say for debugging purposes, it's theoretically possible that moving it outside the loop would improve performance enough to be handy during your debugging efforts. If so, it might be sensible, at least while you're debugging. And although I don't think it's likely to make any difference in an optimized build, if you do observe one, you/your pair/your team can make a judgement call as to whether it's worth it.
At the same time, you have to consider not only how the compiler reads your code, but also how it comes off to humans, yourself included. I think you'll agree that a variable declared in the smallest scope possible is easier to keep track of. If it's outside the loop, it implies that it's needed outside the loop, which is confusing if that's not actually the case. In a big codebase, little confusions like this add up over time and become fatiguing after hours of work, and can lead to silly bugs. That can be much more costly than what you reap from a slight performance improvement, depending on the use case.
If you use
android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"
in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:
Intent notificationClick = new Intent(context, NotifyActivity.class);
Bundle bdl = new Bundle();
bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
notificationClick.putExtras(bdl);
notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); // schließt tasks der app und startet einen seperaten neuen
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotifyActivity.class);
stackBuilder.addNextIntent(notificationClick);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(notificationPendingIntent);
Important is to set unique data e.g. using an unique id like:
notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:
systemProp.http.proxyHost=proxyURL
systemProp.http.proxyPort=proxyPort
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.https.proxyHost=proxyUrl
systemProp.https.proxyPort=proxyPort
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD
Where : proxyUrl is the url of the proxy server (http://.....)
proxyPort is the port (usually 8080)
USER is my domain user
PASSWORD, my password
In this case, the proxy for http and https is the same
The WITH
clause for Common Table Expressions go at the top.
Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.
Spot the mistake:
WITH _INSERT_ AS (
SELECT
[BatchID] = blah
,[APartyNo] = blahblah
,[SourceRowID] = blahblahblah
FROM Table1 AS t1
)
INSERT Table2
([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]
FROM _INSERT_
Same mistake:
INSERT Table2 (
[BatchID]
,[SourceRowID]
,[APartyNo]
)
SELECT
[BatchID] = blah
,[APartyNo] = blahblah
,[SourceRowID] = blahblahblah
FROM Table1 AS t1
A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.
Mozilla Developer Network has a nice description and example of onbeforeunload.
If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = ...; //you implement this logic...
if(myPageIsDirty) {
//following two lines will cause the browser to ask the user if they
//want to leave. The text of this dialog is controlled by the browser.
e.preventDefault(); //per the standard
e.returnValue = ''; //required for Chrome
}
//else: user is allowed to leave without a warning dialog
});
The Kotlin ktx way to clear all preferences:
val prefs: SharedPreferences = getSharedPreferences("prefsName", Context.MODE_PRIVATE)
prefs.edit(commit = true) {
clear()
}
Click here for all Shared preferences operations with examples
=>
is used in associative array key value assignment. Take a look at:
http://php.net/manual/en/language.types.array.php.
->
is used to access an object method or property. Example: $obj->method()
.
List<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
HashSet<String> hs=new HashSet<>(list);
System.out.println("=========With Duplicate Element========");
System.out.println(list);
System.out.println("=========Removed Duplicate Element========");
System.out.println(hs);
If anyone looking with time and timezone, this is for you
{{data.ct | date :'dd-MMM-yy h:mm:ss a '}}
add z for time zone at the end of date and time format
{{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}
Here's pure javascript example of handling classes during scrolling.
You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle
from lodash
lib comes in handy.
And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener
once they're not needed (eg during onDestroy
lifecycle hook of your component, like destroyed()
for Vue, or maybe return function of useEffect
hook for React).
const navbar = document.getElementById('navbar')_x000D_
_x000D_
// OnScroll event handler_x000D_
const onScroll = () => {_x000D_
_x000D_
// Get scroll value_x000D_
const scroll = document.documentElement.scrollTop_x000D_
_x000D_
// If scroll value is more than 0 - add class_x000D_
if (scroll > 0) {_x000D_
navbar.classList.add("scrolled");_x000D_
} else {_x000D_
navbar.classList.remove("scrolled")_x000D_
}_x000D_
}_x000D_
_x000D_
// Optional - throttling onScroll handler at 100ms with lodash_x000D_
const throttledOnScroll = _.throttle(onScroll, 100, {})_x000D_
_x000D_
// Use either onScroll or throttledOnScroll_x000D_
window.addEventListener('scroll', onScroll)
_x000D_
#navbar {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: 100%;_x000D_
height: 60px;_x000D_
background-color: #89d0f7;_x000D_
box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);_x000D_
transition: box-shadow 500ms;_x000D_
}_x000D_
_x000D_
#navbar.scrolled {_x000D_
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
#content {_x000D_
height: 3000px;_x000D_
margin-top: 60px;_x000D_
}
_x000D_
<!-- Optional - lodash library, used for throttlin onScroll handler-->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>_x000D_
<header id="navbar"></header>_x000D_
<div id="content"></div>
_x000D_
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
There is an old plugin called HEX Editor here.
According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.
Why not use the PDFMergerUtility of pdfbox?
PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(...);
ut.addSource(...);
ut.addSource(...);
ut.setDestinationFileName(...);
ut.mergeDocuments();
Yes you can create events on objects, here is an example;
public class Foo
{
public delegate void MyEvent(object sender, object param);
event MyEvent OnMyEvent;
public Foo()
{
this.OnMyEvent += new MyEvent(Foo_OnMyEvent);
}
void Foo_OnMyEvent(object sender, object param)
{
if (this.OnMyEvent != null)
{
//do something
}
}
void RaiseEvent()
{
object param = new object();
this.OnMyEvent(this,param);
}
}
Use this following very simple JAVA 8 Runnable Class feature
public class MultiThreadExample {
static AtomicInteger atomicNumber = new AtomicInteger(1);
public static void main(String[] args) {
Runnable print = () -> {
while (atomicNumber.get() < 10) {
synchronized (atomicNumber) {
if ((atomicNumber.get() % 2 == 0) && "Even".equals(Thread.currentThread().getName())) {
System.out.println("Even" + ":" + atomicNumber.getAndIncrement());
} else if ((atomicNumber.get() % 2 != 0) && "Odd".equals(Thread.currentThread().getName())) {
System.out.println("Odd" + ":" + atomicNumber.getAndIncrement());
}
}
}
};
Thread t1 = new Thread(print);
t1.setName("Even");
t1.start();
Thread t2 = new Thread(print);
t2.setName("Odd");
t2.start();
}
}
You can put the above answers into one line like this. And you don't need to write the function.
<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;" />
This is how I did it
// sets Asia/Calcutta time zone
date_default_timezone_set("Asia/Calcutta");
//fetches current date and time
$date = date("Y-m-d H:i:s");
$dateArray = date_parse_from_format('Y/m/d', $date);
$month = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
$dateString = $dateArray['day'] . " " . $month . " " . $dateArray['year'];
echo $dateString;
returns 30 June 2019
you can use the download attribute on an a tag ...
<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download
In java script calculate width using following code
var scrollX = $(window).width()*58/100;
var oTable = $('#reqAllRequestsTable').dataTable({
"sScrollX": scrollX
} );
Let us look at where one would use Runnable and Callable.
Runnable and Callable both run on a different thread than the calling thread. But Callable can return a value and Runnable cannot. So where does this really apply.
Runnable : If you have a fire and forget task then use Runnable. Put your code inside a Runnable and when the run() method is called, you can perform your task. The calling thread really does not care when you perform your task.
Callable : If you are trying to retrieve a value from a task, then use Callable. Now callable on its own will not do the job. You will need a Future that you wrap around your Callable and get your values on future.get (). Here the calling thread will be blocked till the Future comes back with results which in turn is waiting for Callable's call() method to execute.
So think about an interface to a target class where you have both Runnable and Callable wrapped methods defined. The calling class will randomly call your interface methods not knowing which is Runnable and which is Callable. The Runnable methods will execute asynchronously, till a Callable method is called. Here the calling class's thread will block since you are retrieving values from your target class.
NOTE : Inside your target class you can make the calls to Callable and Runnable on a single thread executor, making this mechanism similar to a serial dispatch queue. So as long as the caller calls your Runnable wrapped methods the calling thread will execute really fast without blocking. As soon as it calls a Callable wrapped in Future method it will have to block till all the other queued items are executed. Only then the method will return with values. This is a synchronization mechanism.
If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.
$('.your-class').owlCarousel({
loop: true,
items: 1, // Select Item Number
autoplay:true,
dots: false,
nav: true,
navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],
});
You should add the ngDefaultControl attribute to your input like this:
<md-input
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
class="col-sm-4"
(blur)="addRecipient(recipient)"
ngDefaultControl>
</md-input>
Taken from comments in this post:
angular2 rc.5 custom input, No value accessor for form control with unspecified name
Note: For later versions of @angular/material:
Nowadays you should instead write:
<md-input-container>
<input
mdInput
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
(blur)="addRecipient(recipient)">
</md-input-container>
I think, the statement
everyone hates it except me
makes any further discussion waste: when you keep using Git, they will blame you if anything goes wrong.
Apart from this, for me Git has two advantages over a centralized VCS that I appreciate most (as partly described by Rob Sobers):
But as I said: I think that you're fighting a lost battle: when everyone hates Git, don't use Git. It could help you more to know why they hate Git instead of trying them to convince them.
If they simply don't want it 'cause it's new to them and are not willing to learn something new: are you sure that you will do successful development with that staff?
Does really every single person hate Git or are they influenced by some opinion leaders? Find the leaders and ask them what's the problem. Convince them and you'll convince the rest of the team.
If you cannot convince the leaders: forget about using Git, take the TFS. Will make your life easier.
Navigate to Window > Preferences > General > Editors > Text Editors
Click on the CheckBox "Show whitespace characters".
Thats all.!!!
Since PHP 7.3 (2018) there is (finally) function for this: http://php.net/manual/en/function.array-key-last.php
$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )
will output
orange
According to Apple documentation
Example :
var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow
Get-PSDrive C | Select-Object @{ E={$_.Used/1GB}; L='Used' }, @{ E={$_.Free/1GB}; L='Free' }
Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!
You can make this method static.
public static void startChronometer(){
mChronometer.start();
showElapsedTime();
}
you can call this function in other class as below:
MainActivity.startChronometer();
OR
You can make an object of the main class in second class like,
MainActivity mActivity = new MainActivity();
mActivity.startChronometer();
try:
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.
See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/
There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php
to redirect from /folder1 to /apple try this:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
to redirect and then rewrite just combine the above in the htaccess file:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.
I had this issue with a WinForms Project using VS 2015. My solution was:
One thing that might not always be obvious to some is that a cross join with an empty table (or result set) results in empty table (M x N; hence M x 0 = 0)
A full outer join will always have rows unless both M and N are 0.
x86 is for a 32-bit OS, and x64 is for a 64-bit OS
Difference between app.use
& app.get
:
app.use
? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.
app.get
? It is only for handling GET HTTP requests.
Now, there is a confusion between app.use
& app.all
. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests.
But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.
app.use()
? It takes only one callback.
app.all()
? It can take multiple callbacks.
app.use()
will only see whether url starts with specified path.
But, app.all()
will match the complete path.
For example,
app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
app.all( "/book" , handler);
// will match /book
// won't match /book/author
// won't match /book/subject
app.all( "/book/*" , handler);
// won't match /book
// will match /book/author
// will match /book/subject
next()
call inside the app.use()
will call either the next middleware or any route handler, but next()
call inside app.all()
will invoke the next route handler (app.all()
, app.get/post/put...
etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.My problem was that I was using the HTML <base>
tag to change the base URL of my test site. Once I removed that tag from the header, the $_POST
data came back.
Modifications to sys.path
only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH
environment variable:
PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH
Note that PATH
is the system path for executables, which is completely separate.
**You can write the above in ~/.bash_profile
and the source it using source ~/.bash_profile
If you're using Python3.x input
will return a string,so you should use int
method to convert string to integer.
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
By the way,it's a good way to use try
catch
if you want to convert string to int:
try:
i = int(s)
except ValueError as err:
pass
Hope this helps.
You specified both jQuery and Javascript in the tags so here's both approaches.
jQuery
var selector = '.nav li';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/
Pure Javascript:
var selector, elems, makeActive;
selector = '.nav li';
elems = document.querySelectorAll(selector);
makeActive = function () {
for (var i = 0; i < elems.length; i++)
elems[i].classList.remove('active');
this.classList.add('active');
};
for (var i = 0; i < elems.length; i++)
elems[i].addEventListener('mousedown', makeActive);
Fiddle: http://jsfiddle.net/rn3nc/1
jQuery with event delegation:
Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new li
s to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav
:
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/1/
The subtle difference is that the handler is bound to the .nav
now, so when you click the li
the event bubbles up the DOM to the .nav
which invokes the handler if the element clicked matches your selector
argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.
It's really quite interesting. Read more about it here: http://api.jquery.com/on/
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
You need to install this
https://pypi.python.org/pypi/six
If you still don't know what pip is , then please also google for pip install
Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/
bootstrap 3 has a class to align the text within a div
<div class="text-right">
will align the text on the right
<div class="pull-right">
will pull to the right all the content not only the text
Your update syntax is incorrect. Please check Update Syntax for the correct syntax.
$sql = "UPDATE `access_users` set `contact_first_name` = :firstname, `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:
Draconian synchronization:
private static YourObject instance;
public static synchronized YourObject getInstance() {
if (instance == null) {
instance = new YourObject();
}
return instance;
}
This solution requires that every thread be synchronized when in reality only the first few need to be.
private static final Object lock = new Object();
private static volatile YourObject instance;
public static YourObject getInstance() {
YourObject r = instance;
if (r == null) {
synchronized (lock) { // While we were waiting for the lock, another
r = instance; // thread may have instantiated the object.
if (r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.
private static class InstanceHolder {
private static final YourObject instance = new YourObject();
}
public static YourObject getInstance() {
return InstanceHolder.instance;
}
This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance
is called, InstanceHolder
will be loaded and instance
will be created, and since this is controlled by ClassLoader
s, no additional synchronization is necessary.
This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.
I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type
which, for my situation, worked. (So, thanks for that, @Bdwey.)
I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.
Turns out as follows: div.myclass:nth-of-type(2)
does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening div
s between your div.myclass
instances.
It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1
, h2
, h3
and h4
elements to essentially be div
s. I've put an A
class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?)
. (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h
level) or similar (i.e. same h
level) un-classed element into some of the groups.
Note, in particular, the last grouping of 3. Here, an un-classed h3
element is inserted between the first and second h3.A
elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A
. This shows that the n
in h3.A:nth-of-type(n)
is counting the h3
s, not the h3.A
s.
Well, hope that helps. And thanks, @BoltClock.
div {_x000D_
margin-bottom: 2em;_x000D_
border: red solid 1px;_x000D_
background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
font-size: 12pt;_x000D_
margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
<h1 class="A">h1.A #1</h1>_x000D_
<h1 class="A">h1.A #2</h1>_x000D_
<h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h2 class="A">h2.A #1</h2>_x000D_
<h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
<h2 class="A">h2.A #2</h2>_x000D_
<h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h3 class="A">h3.A #1</h3>_x000D_
<h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
<h3 class="A">h3.A #2</h3>_x000D_
<h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the @ prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && @$_GET['var']!='' ){
//Is not empty, do something
}
XSLT stylesheets must be well-formed XML. Since " "
is not one of the five predefined XML entities, it cannot be directly included in the stylesheet.
So coming back to your solution " "
is a perfect replacement of " "
you should use.
Example:
<xsl:value-of select="$txtFName"/> <xsl:value-of select="$txtLName"/>
You have to put them on one line like this:
li:nth-child(2) {
transform: rotate(15deg) translate(-20px,0px);
}
When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.
Keep in mind multiple transform one line directives are applied from right to left.
This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);
will not produce the same result:
.orderOne, .orderTwo {_x000D_
font-family: sans-serif;_x000D_
font-size: 22px;_x000D_
color: #000;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
A_x000D_
</div>
_x000D_
With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.
I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:
When no input has been given yet, I would advise:
touchUi = true
on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.
My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.
Edit: Result
<div fxLayout="row">
<div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
<mat-form-field>
<input matInput [ngxTimepicker]="endTime" [format]="24" placeholder="{{placeholderTime}}" formControlName="endTime" />
</mat-form-field>
<ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
</div>
<div>
<mat-form-field>
<input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
[min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
<mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
<mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
</mat-form-field>
</div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';
import * as moment_ from 'moment';
const moment = moment_;
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
class DateConfig {
startView: 'month' | 'year' | 'multi-year';
touchUi: boolean;
minDate: moment_.Moment;
maxDate: moment_.Moment;
}
@Component({
selector: 'cb-datetimepicker',
templateUrl: './cb-datetimepicker.component.html',
styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {
@Input() disabled: boolean;
@Input() placeholderDate: string;
@Input() placeholderTime: string;
@Input() model: Date;
@Input() purpose: string;
@Input() dateOnly: boolean;
@Output() dateUpdate = new EventEmitter<Date>();
public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);
public dateForm: FormControl;
public timeFormGroup: FormGroup;
public endTime: FormControl;
public momentDate: moment_.Moment;
public config: DateConfig;
//myGroup: FormGroup;
constructor(private adapter : DateAdapter<any>) { }
ngOnInit() {
this.adapter.setLocale("nl-NL");//todo: configurable
this.config = new DateConfig();
if (this.purpose === "birthday") {
this.config.startView = 'multi-year';
this.config.maxDate = moment().add('year', -15);
this.config.minDate = moment().add('year', -90);
this.dateOnly = true;
} //add more configurations
else {
this.config.startView = 'month';
this.config.maxDate = moment().add('year', 100);
this.config.minDate = moment().add('year', -100);
}
if (window.screen.width < 767) {
this.config.touchUi = true;
}
if (this.model) {
var mom = moment(this.model);
if (mom.isBefore(moment('1900-01-01'))) {
this.momentDate = moment();
} else {
this.momentDate = mom;
}
} else {
this.momentDate = moment();
}
this.dateForm = new FormControl(this.momentDate);
if (this.disabled) {
this.dateForm.disable();
}
this.endTime = new FormControl(this.momentDate.format("HH:mm"));
this.timeFormGroup = new FormGroup({
endTime: this.endTime
});
}
public dateChange(date: MatDatepickerInputEvent<any>) {
if (moment.isMoment(date.value)) {
this.momentDate = moment(date.value);
if (this.dateOnly) {
this.momentDate = this.momentDate.utc(true);
}
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
console.log("datechange",date);
}
public timeChange(time: string) {
var splitted = time.split(':');
var hour = splitted[0];
var minute = splitted[1];
console.log("time change", time);
this.momentDate = this.momentDate.set('hour', parseInt(hour));
this.momentDate = this.momentDate.set('minute', parseInt(minute));
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
}
One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126
I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).
>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&
Or in other words: '\\&'
only contains one backslash. It's just escaped in the python shell's output for clarity.
You can try this as well, which is really a combination of previous answers from other posters here :
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "RubberMat")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
No such thing as abstract variables in Java (or C++).
If the parent class has a variable, and a child class extends the parent, then the child doesn't need to implement the variable. It just needs access to the parent's instance. Either get/set or protected access will do.
"...so I should be prompted to implement the abstracts"? If you extend an abstract class and fail to implement an abstract method the compiler will tell you to either implement it or mark the subclass as abstract. That's all the prompting you'll get.
I guess this is also possible like this?
var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));
Is "TakeWhile" worse than "Where" in sense of performance or clarity?
I just thought that I'd add that there is a notion of Z-order in Swing, see [java.awt.Component#setComponentZOrder][1]
which affects the positions of a component in its parents component array, which determines the painting order.
Note that you should override javax.swing.JComponent#isOptimizedDrawingEnabled to return false in the parent container to get your overlapping components to repaint correctly, otherwise their repaints will clobber each other. (JComponents assume no overlapping children unless isOptimizedDrawingEnabled returns false)
You can use the following multiplot
function from Winston Chang's R cookbook
multiplot(plot1, plot2, cols=2)
multiplot <- function(..., plotlist=NULL, cols) {
require(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# Make the panel
plotCols = cols # Number of columns of plots
plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
# Make each plot, in the correct location
for (i in 1:numPlots) {
curRow = ceiling(i/plotCols)
curCol = (i-1) %% plotCols + 1
print(plots[[i]], vp = vplayout(curRow, curCol ))
}
}
Does not work with Tables, only functions etc.
Here is a site with some examples.
if you are using SQL 2012 you should try
SELECT ID,
AccountID,
Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT,
FROM tCariH
if available, better order by date column.
To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release
I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:
But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:
This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).
=COUNTIF(A:A;"lisa")
You can replace the criteria with cell references from Column B
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
This code will work for Swift 4.2.
let controller:SecondViewController =
self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as!
SecondViewController
controller.view.frame = self.view.bounds;
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
To set JDK you can watch this video : how to set JDK . Then when you'll have JDK:
I did it with jQuery:
page.execute_script %Q{ $('#some_id').prop('checked', true) }
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
Date can be compared in sqlserver using string comparision: e.g.
DECLARE @strDate VARCHAR(15)
SET @strDate ='07-12-2010'
SELECT * FROM table
WHERE CONVERT(VARCHAR(15),dtInvoice, 112)>= CONVERT(VARCHAR(15),@strDate , 112)
The simplest solution is to add this CSS to the children:
.your-child {
pointer-events: none;
}
You have to copy the bits over a new image with the target resolution, like this:
using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
{
using (Bitmap newBitmap = new Bitmap(bitmap))
{
newBitmap.SetResolution(300, 300);
newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
}
}
Here's a solution using a negative lookahead (not supported in all regex engines):
^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$
Test that it works as expected:
import re
tests = [
('a', True),
('_', False),
('zz', True),
('a0', True),
('A_', False),
('a0_b', True),
('a__b', False),
('a_1_c', True),
]
regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
is_match = re.match(regex, test[0]) is not None
if is_match != test[1]:
print "fail: " + test[0]
please try this with bootstrap:
<div class="text-center d-flex">
<hr className="flex-grow-1" />
<span className="px-2 font-weight-lighter small align-self-center">
Hello
</span>
<hr className="flex-grow-1" />
</div>
No there isn't. You can only read information associated with the current domain.
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}
LOGO refers to your image
Hoping to help anyone. :)
One option from dplyr 1.0.0
could be:
DF %>%
rowwise() %>%
mutate(row_max = names(.)[which.max(c_across(everything()))])
V1 V2 V3 row_max
<dbl> <dbl> <dbl> <chr>
1 2 7 9 V3
2 8 3 6 V1
3 1 5 4 V2
Sample data:
DF <- structure(list(V1 = c(2, 8, 1), V2 = c(7, 3, 5), V3 = c(9, 6,
4)), class = "data.frame", row.names = c(NA, -3L))
My absolute favorite description of the difference between unchecked and checked exceptions is provided by the Java Tutorial trail article, "Unchecked Exceptions - the Controversy" (sorry to get all elementary on this post - but, hey, the basics are sometimes the best):
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception
The heart of "what type of exception to throw" is semantic (to some degree) and the above quote provides and excellent guideline (hence, I am still blown away by the notion that C# got rid of checked exceptions - particularly as Liskov argues for their usefulness).
The rest then becomes logical: to which exceptions does the compiler expect me to respond, explicitly? The ones from which you expect client to recover.
Pass in the straight XML instead of a dictionary.
Just happened to me, and turned out to be different than all other cases listed here.
I happen to have two virtual servers hosted in the same cluster, each with it own IP address. The host configured one of the servers to be the SQL Server, and the other to be the Web server. However, SQL Server is installed and running on both. The host forgot to mention which of the servers is the SQL and which is the Web, so I just assumed the first is Web, second is SQL.
When I connected to the (what I thought is) SQL Server and tried to connect via SSMS, choosing Windows Authentication, I got the error mentioned in this question. After pulling lots of hairs, I went over all the setting, including SQL Server Network Configuration, Protocols for MSSQLSERVER:
Double clicking the TCP/IP gave me this:
The IP address was of the other virtual server! This finally made me realize I simply confused between the servers, and all worked well on the second server.
Get the precompiled binaries from http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/
Download pkg-config and its depend libraries :
Unix/Cygwin only, pipe it through 'tr':
mysql <database> -e "<query here>" | tr '\t' ',' > data.csv
N.B.: This handles neither embedded commas, nor embedded tabs.
This works in May 2020 using PDFminer six in Python3.
$ pip install pdfminer.six
from pdfminer.high_level import extract_text
text = extract_text('report.pdf')
Or alternatively:
with open('report.pdf','rb') as f:
text = extract_text(f)
If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io
library:
import io
response = requests.get(url)
text = extract_text(io.BytesIO(response.content))
PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7
However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.
I timed text extraction with timeit
on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:
PDFminer.six: 2.88 sec
PyPDF2: 0.45 sec
pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.
For MIUI 9.6 works:
1. Become a developer: Settings >> About phone >> MIUI version tap 7 times.
2. Again Settings >> Additional settings >> Developer options (turn on) >> USB debugging (turn on) >> Install via USB (turn on).
3. You will be asked for permission through your MI account. Confirm permission.
4. Note: During the installation of the application, your device will give you 7 seconds to confirm the installation. Don't miss it!
In PostgreSQL, another possibility is to use the first_value
window function in combination with SELECT DISTINCT
:
select distinct customer_id,
first_value(row(id, total)) over(partition by customer_id order by total desc, id)
from purchases;
I created a composite (id, total)
, so both values are returned by the same aggregate. You can of course always apply first_value()
twice.
Here's a generic multidimensional sort, allowing for reversing and/or mapping on each level.
Written in Typescript. For Javascript, check out this JSFiddle
type itemMap = (n: any) => any;
interface SortConfig<T> {
key: keyof T;
reverse?: boolean;
map?: itemMap;
}
export function byObjectValues<T extends object>(keys: ((keyof T) | SortConfig<T>)[]): (a: T, b: T) => 0 | 1 | -1 {
return function(a: T, b: T) {
const firstKey: keyof T | SortConfig<T> = keys[0];
const isSimple = typeof firstKey === 'string';
const key: keyof T = isSimple ? (firstKey as keyof T) : (firstKey as SortConfig<T>).key;
const reverse: boolean = isSimple ? false : !!(firstKey as SortConfig<T>).reverse;
const map: itemMap | null = isSimple ? null : (firstKey as SortConfig<T>).map || null;
const valA = map ? map(a[key]) : a[key];
const valB = map ? map(b[key]) : b[key];
if (valA === valB) {
if (keys.length === 1) {
return 0;
}
return byObjectValues<T>(keys.slice(1))(a, b);
}
if (reverse) {
return valA > valB ? -1 : 1;
}
return valA > valB ? 1 : -1;
};
}
Sorting a people array by last name, then first name:
interface Person {
firstName: string;
lastName: string;
}
people.sort(byObjectValues<Person>(['lastName','firstName']));
Sort language codes by their name, not their language code (see map
), then by descending version (see reverse
).
interface Language {
code: string;
version: number;
}
// languageCodeToName(code) is defined elsewhere in code
languageCodes.sort(byObjectValues<Language>([
{
key: 'code',
map(code:string) => languageCodeToName(code),
},
{
key: 'version',
reverse: true,
}
]));
quote
and hashtag
parameters work as of Dec 2018.Does anyone know if there have been recent changes which could have suddenly stopped this from working?
The parameters have changed. The currently accepted answer states:
Facebook no longer supports custom parameters in
sharer.php
But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:
u
picture
title
quote
description
caption
For instance, you can share this very question with the following URL:
https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook"e=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.
I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php
link, just press the button and copy the URL from the tab that opens.
Simple. Use splitlines()
L = open("myFile.txt", "r").read().splitlines();
for line in L:
process(line) # this 'line' will not have '\n' character at the end
A simpler solution on recent versions of tmux (tested on 1.9) you can now do :
tmux detach -a
-a
is for all other client on this session except the current one
You can alias it in your .[bash|zsh]rc
alias takeover="tmux detach -a"
Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover
.
I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)
This is because findViewById()
searches in the activity_main
layout, while the button is located in the fragment's layout fragment_main
.
Move that piece of code in the onCreateView()
method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView
view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
Improved version of what Ustaman Sangat did
static inline uint64_t
log2(uint64_t n)
{
uint64_t val;
for (val = 0; n > 1; val++, n >>= 1);
return val;
}
if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
@Test
public void findAllHavingAddressLike() {
CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
CriteriaQuery<Instructor> cq = cb.createQuery(Instructor.class);
Root<Instructor> root = cq.from(Instructor.class);
printResultList(cq.select(root).where(
cb.like(root.get(Instructor_.address), "%#1074%")));
}
Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.
I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.
I think that what you have to check is:
if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).
dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).
To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.
Sub test_date_or_String()
Set c = ActiveCell
c.NumberFormat = "@"
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
c.NumberFormat = "m/d/yyyy"
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date
End Sub
Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).
As for wrappers, the best ones i've used (as previously suggested) are:
and
best of luck!
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.
Having said that, I would go with the first option:
git add foo.js
git commit foo.js -m "commit"
git pull
git push
Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.
I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.
You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.
public class Apple {
public Apple(Integer i){this.i=i; }
}
but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
For this you can simply use the "HttpWebRequest" and "HttpWebResponse" classes in .net.
Below is a sample console app I wrote to demonstrate how easy this is.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string url = "www.somewhere.com";
string fileName = @"C:\output.file";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 5000;
try
{
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] bytes = ReadFully(response.GetResponseStream());
stream.Write(bytes, 0, bytes.Length);
}
}
}
catch (WebException)
{
Console.WriteLine("Error Occured");
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}
Enjoy!
The answers referring to simply calling array()
are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap
an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):
if (myByteBuffer.hasArray()) {
return new String(myByteBuffer.array(),
myByteBuffer.arrayOffset() + myByteBuffer.position(),
myByteBuffer.remaining());
} else {
final byte[] b = new byte[myByteBuffer.remaining()];
myByteBuffer.duplicate().get(b);
return new String(b);
}
For the concerns related to encoding, see Andy Thomas' answer.
That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead
See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim
script for launching from the command line
import numpy as np
a=np.array([[21,20,19,18,17],[16,15,14,13,12],[11,10,9,8,7],[6,5,4,3,2]])
y=np.argsort(a[:,2],kind='mergesort')# a[:,2]=[19,14,9,4]
a=a[y]
print(a)
Desired output is [[6,5,4,3,2],[11,10,9,8,7],[16,15,14,13,12],[21,20,19,18,17]]
note that argsort(numArray)
returns the indices of an numArray
as it was supposed to be arranged in a sorted manner.
example
x=np.array([8,1,5])
z=np.argsort(x) #[1,3,0] are the **indices of the predicted sorted array**
print(x[z]) #boolean indexing which sorts the array on basis of indices saved in z
answer would be [1,5,8]
A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:
class ChangeKeyValueForm(forms.ModelForm):
_terminal_list = forms.ModelMultipleChoiceField(
queryset=Terminal.objects.all() )
class Meta:
model = ChangeKeyValue
fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time', ]
class ChangeKeyValueAdmin(admin.ModelAdmin):
form = ChangeKeyValueForm
list_display = ('terminal','task_list', 'plugin','last_update_time')
list_per_page =16
def get_form(self, request, obj = None, **kwargs):
form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
qs, filterargs = Terminal.get_list(request)
form.base_fields['_terminal_list'].queryset = qs
return form
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
I had the following scenario that was causing the same error:
Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.
It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":
using (var wc = new WebClient())
{
var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
tskResult.Wait();
}
Here's another way:
fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"
Put parentheses around the "OR"s:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
Or even better, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
You have to shrink & backup the log a several times to get the log file to reduce in size, this is because the the log file pages cannot be re-organized as data files pages can be, only truncated. For a more detailed explanation check this out.
WARNING : Detaching the db & deleting the log file is dangerous! don't do this unless you'd like data loss
I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.
It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.
All methods mention here are not working for me. I built Subversion from source, and I found out, I must run configure with --enable-plaintext-password-storage
to support this feature.
The most elegant solution is to use itertools.product in python 2.6.
If you aren't using Python 2.6, the docs for itertools.product actually show an equivalent function to do the product the "manual" way:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
I find it easier to work with the Version
class:
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace System.Runtime.InteropServices {
public static class RuntimeInformationEx {
public static Version? GetDotnetFrameworkVersion() {
using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full");
if (key is object) {
if (!Int32.TryParse(key.GetValue("Release", "").ToString(), out var release)) return null;
return release switch
{
378389 => new Version(4, 5, 0),
378675 => new Version(4, 5, 1),
378758 => new Version(4, 5, 1),
379893 => new Version(4, 5, 2),
393295 => new Version(4, 6, 0),
393297 => new Version(4, 6, 0),
394254 => new Version(4, 6, 1),
394271 => new Version(4, 6, 1),
394802 => new Version(4, 6, 2),
394806 => new Version(4, 6, 2),
460798 => new Version(4, 7, 0),
460805 => new Version(4, 7, 0),
461308 => new Version(4, 7, 1),
461310 => new Version(4, 7, 1),
461808 => new Version(4, 7, 2),
461814 => new Version(4, 7, 2),
528040 => new Version(4, 8, 0),
528209 => new Version(4, 8, 0),
528049 => new Version(4, 8, 0),
_ => null
};
} else { // .NET version < 4.5
using var key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
if (key1 is null) return null;
var parts = key1.GetSubKeyNames()[^1].Substring(1).Split('.'); // get lastsub key, remove 'v' prefix, and split
if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
if (parts.Length != 3) return null;
Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
}
}
public static Version? GetDotnetCoreVersion() {
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Core ")) return null;
var parts = RuntimeInformation.FrameworkDescription.Substring(10).Split('.');
if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
if (parts.Length != 3) return null;
Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
}
}
}
(code is C#8)
While I realize this is not a keyboard shortcut, I figured I would add this, as it does not require the usage of the clipboard and might help some people.
Highlight the row you want to duplicate. Press control, mouse click the highlighted text, and drag to where you want to go to. It will duplicate the highlighted text.
It turns out there is no one mentioning set spring.jpa.database=mysql
in application.properties
file, if you use Spring JPA. This is the simplest answer to me and I want to share in this question.
From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
occurred because dispatch_group_t
was released while it was still locking (waiting for dispatch_group_leave
).
According to what you found, this was what happened :
dispatch_group_t group
was created. group
's retain count = 1.-[self webservice:onCompletion:]
captured the group
. group
's retain count = 2.dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... });
captured the group
again. group
's retain count = 3.group
was released. group
's retain count = 2.dispatch_group_leave
was never called.dispatch_group_wait
was timeout. The dispatch_async
block was completed. group
was released. group
's retain count = 1.-[self webservice:onCompletion:]
was called again, the old onCompletion
block was replaced with the new one. So, the old group
was released. group
's retain count = 0. group
was deallocated. That resulted to EXC_BAD_INSTRUCTION
.To fix this, I suggest you should find out why -[self webservice:onCompletion:]
didn't call onCompletion
block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.
In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group
for you :
DISPATCH_TIME_FOREVER
or a reasonable amount of time that all -[self webservice:onCompletion]
should call their onCompletion
blocks by the time. So that the block in dispatch_async(...)
will hold it for you.group
into a collection, such as NSMutableArray
.I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t
or dispatch_semaphore_t
.
int main()
{
int array[11];
printf("Write down your ID number!\n");
for(int i=0;i<id_length;i++)
scanf("%d", &array[i]);
if (array[0]==1)
{
printf("\nThis person is a male.");
}
else if (array[0]==2)
{
printf("\nThis person is a female.");
}
return 0;
}
Swift 4.x
Put this in some file:
func background(work: @escaping () -> ()) {
DispatchQueue.global(qos: .userInitiated).async {
work()
}
}
func main(work: @escaping () -> ()) {
DispatchQueue.main.async {
work()
}
}
and then call it where you need:
background {
//background job
main {
//update UI (or what you need to do in main thread)
}
}
They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).
In your example "HelveticaNeue-Light"
will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light"
and finally "Helvetica Neue"
.
As far as I'm aware "Helvetica Neue"
isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif"
or "sans-serif"
as a final default position.
In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.
A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.
Building on some of the answers here, but using some simple math for a smooth transition using a sine curve:
scrollTo(element, from, to, duration, currentTime) {
if (from <= 0) { from = 0;}
if (to <= 0) { to = 0;}
if (currentTime>=duration) return;
let delta = to-from;
let progress = currentTime / duration * Math.PI / 2;
let position = delta * (Math.sin(progress));
setTimeout(() => {
element.scrollTop = from + position;
this.scrollTo(element, from, to, duration, currentTime + 10);
}, 10);
}
Usage:
// Smoothly scroll from current position to new position in 1/2 second.
scrollTo(element, element.scrollTop, element.scrollTop + 400, 500, 0);
PS. take note of ES6 style
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
Chances are that you may be running your eclipse using Java 1.5.
Latest Plugin requires that the JRE be 1.6 or higher.
You will have to use Eclipse that runs on JRE 1.6
Edit: I had run into same problems. If it is not JRE problem then you can debug this. Follow below procedure:
If you're currently on the branch you want to rename:
git branch -m new_name
Or else:
git branch -m old_name new_name
You can check with:
git branch -a
As you can see, only the local name changed Now, to change the name also in the remote you must do:
git push origin :old_name
This removes the branch, then upload it with the new name:
git push origin new_name
Click \Build\Select Build Variant...
in Android Studio.
And choose release
.
If you're loading the PDF from a blob this is how you get the first page instead of the last page:
$im->readimageblob($blob);
$im->setiteratorindex(0);
None of the answers they gave you was exhaustive. The problem lies in the Multidex. You must add the library in the app gradle :
implementation 'com.android.support:multidex:1.0.3'
After, add in the defaultConfig of the app gradle :
multiDexEnabled true
Your Application must be of the Multidex type.. You must write it in the manifest :
android:name=".MyApplication"
"MyApplication" must be either the Multidex class, or it must extend it.
imgLiquid (a jQuery Plugin) seems to do what you ask.
Demo:
http://goo.gl/Wk8bU
JsFiddle example:
http://jsfiddle.net/karacas/3CRx7/#base
Javascript
$(function() {
$(".imgLiquidFill").imgLiquid({
fill: true,
horizontalAlign: "center",
verticalAlign: "top"
});
$(".imgLiquidNoFill").imgLiquid({
fill: false,
horizontalAlign: "center",
verticalAlign: "50%"
});
});
Html
<div class="boxSep" >
<div class="imgLiquidNoFill imgLiquid" style="width:250px; height:250px;">
<img alt="" src="http://www.juegostoystory.net/files/image/2010_Toy_Story_3_USLC12_Woody.jpg"/>
</div>
</div>
Check this:
if (
MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//YES ---> Ok IM ALRIGHHT
}
else
{
//NO --->NO IM STUCK
}
Regards
I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
'update to the cell that contains HTML you want converted
.ExecWB 17, 0
'Select all contents in browser
.ExecWB 12, 2
'Copy them
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
'update to cell you want converted HTML pasted in
.Quit
End With
End Sub
HTTP Servers tend to reject old browsers and systems.
The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection
or the system property "http.agent".
Below Function converts the Excel sheet (XLSX format) data to JSON. you can add promise to the function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script>
var ExcelToJSON = function() {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(json_object);
})
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
</script>
Below post has the code for XLS format Excel to JSON javascript code?
Scanning object for first intance of a determinated prop:
var obj = {a:'Saludos',
b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
d:'Hasta luego'
}
function scan (element,list){
var res;
if (typeof(list) != 'undefined'){
if (typeof(list) == 'object'){
for(key in list){
if (typeof(res) == 'undefined'){
res = (key == element)?list[key]:scan(element,list[key]);
}
});
}
}
return res;
}
console.log(scan('a',obj));
Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):
fetch(request, {mode: 'cors'});
However this still requires the server to enable CORS as well, and allow your domain to request the resource.
Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.
You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>
):
fetch(request, {mode: 'no-cors'})
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
There's also the pygame.freetype
module which is more modern, works with more fonts and offers additional functionality.
Create a font object with pygame.freetype.SysFont()
or pygame.freetype.Font
if the font is inside of your game directory.
You can render the text either with the render
method similarly to the old pygame.font.Font.render
or directly onto the target surface with render_to
.
import pygame
import pygame.freetype # Import the freetype module.
pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255,255,255))
# You can use `render` and then blit the text surface ...
text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
screen.blit(text_surface, (40, 250))
# or just `render_to` the target surface.
GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))
pygame.display.flip()
pygame.quit()
You can use native bootstrap validation states (No Custom CSS!):
<div class="form-group has-feedback">
<label class="control-label" for="inputSuccess2">Name</label>
<input type="text" class="form-control" id="inputSuccess2"/>
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box
You can use the .input-group
class like this:
<div class="input-group">
<input type="text" class="form-control"/>
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box
You can still use .input-group
for positioning but just override the default styling to make the two elements appear separate.
Use a normal input group but add the class input-group-unstyled
:
<div class="input-group input-group-unstyled">
<input type="text" class="form-control" />
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
Then change the styling with the following css:
.input-group.input-group-unstyled input.form-control {
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
Also, these solutions work for any input size
I also did a little workaround of my own.
I created a (dropdownOpen) event which I listen to at my ng-select element component and call a function which will close all the other SelectComponent's opened apart from the currently opened SelectComponent.
I modified one function inside the select.ts file like below to emit the event:
private open():void {
this.options = this.itemObjects
.filter((option:SelectItem) => (this.multiple === false ||
this.multiple === true && !this.active.find((o:SelectItem) => option.text === o.text)));
if (this.options.length > 0) {
this.behavior.first();
}
this.optionsOpened = true;
this.dropdownOpened.emit(true);
}
In the HTML I added an event listener for (dropdownOpened):
<ng-select #elem (dropdownOpened)="closeOtherElems(elem)"
[multiple]="true"
[items]="items"
[disabled]="disabled"
[isInputAllowed]="true"
(data)="refreshValue($event)"
(selected)="selected($event)"
(removed)="removed($event)"
placeholder="No city selected"></ng-select>
This is my calling function on event trigger inside the component having ng2-select tag:
@ViewChildren(SelectComponent) selectElem :QueryList<SelectComponent>;
public closeOtherElems(element){
let a = this.selectElem.filter(function(el){
return (el != element)
});
a.forEach(function(e:SelectComponent){
e.closeDropdown();
})
}
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like
sqlCommand.Transaction = transaction;
And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like
sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();
Unordered lists are often created with the intent of using them as a menu, but an li
list item is text. Because the list li
item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a
inside of the li
tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.
<ul id="menu">
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
<li><a href="#">Menu Item 4</a></li>
</ul>
If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href
attribute, text in the <a>
tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href
, but you don't need a link to anywhere.
You could use lots of div
or p
tags for a menu list, but the mouse pointer would be an I-cursor for them also.
You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#"
that points to nowhere is used in anchor tags inside of list tags.
You can set the pointer style in CSS, so that is another option. The href="#"
to nowhere might just be the lazy way to set some styling.
var config = {_x000D_
type: 'line',_x000D_
data: {_x000D_
labels: ["January", "February", "March", "April", "May", "June", "July"],_x000D_
datasets: [{_x000D_
label: "My First dataset",_x000D_
data: [10, 80, 56, 60, 6, 45, 15],_x000D_
fill: false,_x000D_
backgroundColor: "#eebcde ",_x000D_
borderColor: "#eebcde",_x000D_
borderCapStyle: 'butt',_x000D_
borderDash: [5, 5],_x000D_
}]_x000D_
},_x000D_
options: {_x000D_
responsive: true,_x000D_
legend: {_x000D_
position: 'bottom',_x000D_
},_x000D_
hover: {_x000D_
mode: 'label'_x000D_
},_x000D_
scales: {_x000D_
xAxes: [{_x000D_
display: true,_x000D_
scaleLabel: {_x000D_
display: true,_x000D_
labelString: 'Month'_x000D_
}_x000D_
}],_x000D_
yAxes: [{_x000D_
display: true,_x000D_
ticks: {_x000D_
beginAtZero: true,_x000D_
steps: 10,_x000D_
stepValue: 5,_x000D_
max: 100_x000D_
}_x000D_
}]_x000D_
},_x000D_
title: {_x000D_
display: true,_x000D_
text: 'Chart.js Line Chart - Legend'_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
var ctx = document.getElementById("canvas").getContext("2d");_x000D_
new Chart(ctx, config);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.bundle.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
<canvas id="canvas"></canvas>_x000D_
</body>
_x000D_
Use This..... You will love it
<TextView
android:layout_width="fill_parent"
android:layout_height="1px"
android:text=" "
android:background="#anycolor"
android:id="@+id/textView"/>
You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.
Simply add this to your criteria:
criteria.setProjection(Projections.distinct(Projections.property("id")));
Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check as part of the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness after the sql query has been performed.
Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.
Just add onsubmit
event handler for your form:
<form action="insert.php" onsubmit="return myFunction()" method="post">
Remove onclick
from button
and make it input
with type submit
<input type="submit" value="Submit">
And add boolean return statements to your function:
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var ok = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
return false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
First, let's see why this is happening.
The reason is that, surprisingly, when a box has position: absolute
its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.
Here is the relevant part of the CSS specification:
In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.
The simplest approach—as suggested in Winter's answer—is to use padding: inherit
on the absolutely positioned div
. It only works, though, if you don't want the absolutely positioned div
to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:
Add an extra relatively positioned div
(with no padding) around the absolutely positioned div
. That new div
will respect the padding of its parent, and the absolutely positioned div
will then fill it.
The downside, of course, is that you're messing with the HTML simply for presentational purposes.
Repeat the padding (or add to it) on the absolutely positioned element.
The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS
or LESS
you can avoid that problem by using a variable. This is the method I personally use.
To get the key IDs (8 bytes, 16 hex digits), this is the command which worked for me in GPG 1.4.16, 2.1.18 and 2.2.19:
gpg --list-packets <key.asc | awk '$1=="keyid:"{print$2}'
To get some more information (in addition to the key ID):
gpg --list-packets <key.asc
To get even more information:
gpg --list-packets -vvv --debug 0x2 <key.asc
The command
gpg --dry-run --import <key.asc
also works in all 3 versions, but in GPG 1.4.16 it prints only a short (4 bytes, 8 hex digits) key ID, so it's less secure to identify keys.
Some commands in other answers (e.g. gpg --show-keys
, gpg --with-fingerprint
, gpg --import --import-options show-only
) don't work in some of the 3 GPG versions above, thus they are not portable when targeting multiple versions of GPG.
Java has 5 different boolean compare operators: &, &&, |, ||, ^
& and && are "and" operators, | and || "or" operators, ^ is "xor"
The single ones will check every parameter, regardless of the values, before checking the values of the parameters.
The double ones will first check the left parameter and its value and if true
(||
) or false
(&&
) leave the second one untouched.
Sound compilcated? An easy example should make it clear:
Given for all examples:
String aString = null;
AND:
if (aString != null & aString.equals("lala"))
Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.
if (aString != null && aString.equals("lala"))
The first parameter is checked and it returns false
, so the second paramter won't be checked, because the result is false
anyway.
The same for OR:
if (aString == null | !aString.equals("lala"))
Will raise NullPointerException, too.
if (aString == null || !aString.equals("lala"))
The first parameter is checked and it returns true
, so the second paramter won't be checked, because the result is true
anyway.
XOR can't be optimized, because it depends on both parameters.
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
Following are possible ways to see the version:
Method 1: Connect to the instance of SQL Server, and then run the following query:
Select @@version
An example of the output of this query is as follows:
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009
10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Express
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )
Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.
Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG
and ERRORLOG.n
files. The entries may resemble the following:
2011-03-27 22:31:33.50 Server Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )
As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.
Method 4: Connect to the instance of SQL Server, and then run the following query:
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
Note This query works with any instance of SQL Server 2000 or of a later version
Click here this is a good tutorial for both window/ubuntu.
apktool1.5.1.jar download from here.
apktool-install-linux-r05-ibot download from here.
dex2jar-0.0.9.15.zip download from here.
jd-gui-0.3.3.linux.i686.tar.gz (java de-complier) download from here.
framework-res.apk ( Located at your android device /system/framework/)
Procedure:
it will become .zip.
Then extract .zip.
Unzip downloaded dex2jar-0.0.9.15.zip file , copy the contents and paste it to unzip folder.
Open terminal and change directory to unzip “dex2jar-0.0.9.15 “
– cd – sh dex2jar.sh classes.dex (result of this command “classes.dex.dex2jar.jar” will be in your extracted folder itself).
Now, create new folder and copy “classes.dex.dex2jar.jar” into it.
Unzip “jd-gui-0.3.3.linux.i686.zip“ and open up the “Java Decompiler” in full screen mode.
Click on open file and select “classes.dex.dex2jar.jar” into the window.
“Java Decompiler” and go to file > save and save the source in a .zip file.
Create “source_code” folder.
Extract the saved .zip and copy the contents to “source_code” folder.
This will be where we keep your source code.
Extract apktool1.5.1.tar.bz2 , you get apktool.jar
Now, unzip “apktool-install-linux-r05-ibot.zip”
Copy “framework-res.apk” , “.apk” and apktool.jar
Paste it to the unzip “apktool-install-linux-r05-ibot” folder (line no 13).
Then open terminal and type:
– cd
– chown -R : ‘apktool.jar’
– chown -R : ‘apktool’
– chown -R : ‘aapt’
– sudo chmod +x ‘apktool.jar’
– sudo chmod +x ‘apktool’
– sudo chmod +x ‘aapt’
– sudo mv apktool.jar /usr/local/bin
– sudo mv apktool /usr/local/bin
– sudo mv aapt /usr/local/bin
– apktool if framework-res.apk – apktool d .apk
This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout
.
someView.layoutParams = LinearLayout.LayoutParams(100, 200)
This allows to set the width and height (100
and 200
) in a single line.
I believe this would be somewhere close.
INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs
Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max)
. It was not tested with image as data type.
See the documentation:
list.append(x)
- Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
c.append(c)
"appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.
c += c
is equivalent to extend(c)
, which appends the elements of c to c.
I just leave my solution here.
import csv
import numpy as np
with open(name, newline='') as f:
reader = csv.reader(f, delimiter=",")
# skip header
next(reader)
# convert csv to list and then to np.array
data = np.array(list(reader))[:, 1:] # skip the first column
print(data.shape) # => (N, 2)
# sum each row
s = data.sum(axis=1)
print(s.shape) # => (N,)
#the_div input {
margin: 0 auto;
}
I'm not sure if this works in good ol' IE6, so you might have to do this instead.
/* IE 6 (probably) */
#the_div {
text-align: center;
}
Try jQuery.map function, works pretty well with maps.
var mapArray = {_x000D_
"lastName": "Last Name cannot be null!",_x000D_
"email": "Email cannot be null!",_x000D_
"firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
alert("Value is :" + val);_x000D_
alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
UPDATE: Since this answer was written, Visibility
was introduced and provides the best solution to this problem.
You can use Opacity
with an opacity:
of 0.0
to draw make an element hidden but still occupy space.
To make it not occupy space, replace it with an empty Container()
.
EDIT: To wrap it in an Opacity object, do the following:
new Opacity(opacity: 0.0, child: new Padding(
padding: const EdgeInsets.only(
left: 16.0,
),
child: new Icon(pencil, color: CupertinoColors.activeBlue),
))
Google Developers quick tutorial on Opacity: https://youtu.be/9hltevOHQBw
use .empty()
$('select').empty().append('whatever');
you can also use .html()
but note
When
.html()
is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:
alternative: --- If you want only option elements to-be-remove, use .remove()
$('select option').remove();
In case of simple example if your api is below
@POST
@Path("update_accounts")
@Consumes(MediaType.APPLICATION_JSON)
@PermissionRequired(Permissions.UPDATE_ACCOUNTS)
void createLimit(List<AccountUpdateRequest> requestList) throws RuntimeException;
where AccountUpdateRequest :
public class AccountUpdateRequest {
private Long accountId;
private AccountType accountType;
private BigDecimal amount;
...
}
then your postman request would be: http://localhost:port/update_accounts
[
{
"accountType": "LEDGER",
"accountId": 11111,
"amount": 100
},
{
"accountType": "LEDGER",
"accountId": 2222,
"amount": 300
},
{
"accountType": "LEDGER",
"accountId": 3333,
"amount": 1000
}
]
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Extension for @Kleist answer:
Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB)
and file(GLOB_RECURSE)
. With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.
However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.
Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB)
or file(GLOB_RECURSE)
for collect the sources.
I've used
die() {
echo $1
kill $$
}
before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though.
If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../
apiVersion: skaffold/v2beta4
kind: Config
metadata:
name: frontend
build:
artifacts:
- image: nginx-angular-ui
context: ../../../
sync:
# A local build will update dist and sync it to the container
manual:
- src: './dist/apps'
dest: '/usr/share/nginx/html'
docker:
dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
- image: webapi/image
context: ../../../../api/
docker:
dockerfile: ./dockerfile
deploy:
kubectl:
manifests:
- ./.k8s/*.yml
skaffold run -f ./skaffold.yaml
Please see this wiki page for definition of closure.
And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html
Also look at this Q&A: Closures in Java 7
Update: For extensions to System.Diagnostics, providing some of the missing listeners you might want, see Essential.Diagnostics on CodePlex (http://essentialdiagnostics.codeplex.com/)
Frameworks
A: System.Diagnostics.TraceSource, built in to .NET 2.0.
It provides powerful, flexible, high performance logging for applications, however many developers are not aware of its capabilities and do not make full use of them.
There are some areas where additional functionality is useful, or sometimes the functionality exists but is not well documented, however this does not mean that the entire logging framework (which is designed to be extensible) should be thrown away and completely replaced like some popular alternatives (NLog, log4net, Common.Logging, and even EntLib Logging).
Rather than change the way you add logging statements to your application and re-inventing the wheel, just extended the System.Diagnostics framework in the few places you need it.
It seems to me the other frameworks, even EntLib, simply suffer from Not Invented Here Syndrome, and I think they have wasted time re-inventing the basics that already work perfectly well in System.Diagnostics (such as how you write log statements), rather than filling in the few gaps that exist. In short, don't use them -- they aren't needed.
Features you may not have known:
Areas you might want to look at extending (if needed):
Other Recommendations:
Use structed event id's, and keep a reference list (e.g. document them in an enum).
Having unique event id's for each (significant) event in your system is very useful for correlating and finding specific issues. It is easy to track back to the specific code that logs/uses the event ids, and can make it easy to provide guidance for common errors, e.g. error 5178 means your database connection string is wrong, etc.
Event id's should follow some kind of structure (similar to the Theory of Reply Codes used in email and HTTP), which allows you to treat them by category without knowing specific codes.
e.g. The first digit can detail the general class: 1xxx can be used for 'Start' operations, 2xxx for normal behaviour, 3xxx for activity tracing, 4xxx for warnings, 5xxx for errors, 8xxx for 'Stop' operations, 9xxx for fatal errors, etc.
The second digit can detail the area, e.g. 21xx for database information (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warnings, etc), 23xx for another module, etc.
Assigned, structured event id's also allow you use them in filters.
A: Trace.CorrelationManager is very useful for correlating log statements in any sort of multi-threaded environment (which is pretty much anything these days).
You need at least to set the ActivityId once for each logical operation in order to correlate.
Start/Stop and the LogicalOperationStack can then be used for simple stack-based context. For more complex contexts (e.g. asynchronous operations), using TraceTransfer to the new ActivityId (before changing it), allows correlation.
The Service Trace Viewer tool can be useful for viewing activity graphs (even if you aren't using WCF).
A: You may want to create a scope class, e.g. LogicalOperationScope, that (a) sets up the context when created and (b) resets the context when disposed.
This allows you to write code such as the following to automatically wrap operations:
using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
{
// .. do work here
}
On creation the scope could first set ActivityId if needed, call StartLogicalOperation and then log a TraceEventType.Start message. On Dispose it could log a Stop message, and then call StopLogicalOperation.
A: Yes, multiple Trace Sources are useful / important as systems get larger.
Whilst you probably want to consistently log all Warning & above, or all Information & above messages, for any reasonably sized system the volume of Activity Tracing (Start, Stop, etc) and Verbose logging simply becomes too much.
Rather than having only one switch that turns it all either on or off, it is useful to be able to turn on this information for one section of your system at a time.
This way, you can locate significant problems from the usually logging (all warnings, errors, etc), and then "zoom in" on the sections you want and set them to Activity Tracing or even Debug levels.
The number of trace sources you need depends on your application, e.g. you may want one trace source per assembly or per major section of your application.
If you need even more fine tuned control, add individual boolean switches to turn on/off specific high volume tracing, e.g. raw message dumps. (Or a separate trace source could be used, similar to WCF/WPF).
You might also want to consider separate trace sources for Activity Tracing vs general (other) logging, as it can make it a bit easier to configure filters exactly how you want them.
Note that messages can still be correlated via ActivityId even if different sources are used, so use as many as you need.
Q: What log outputs do you use?
This can depend on what type of application you are writing, and what things are being logged. Usually different things go in different places (i.e. multiple outputs).
I generally classify outputs into three groups:
(1) Events - Windows Event Log (and trace files)
e.g. If writing a server/service, then best practice on Windows is to use the Windows Event Log (you don't have a UI to report to).
In this case all Fatal, Error, Warning and (service-level) Information events should go to the Windows Event Log. The Information level should be reserved for these type of high level events, the ones that you want to go in the event log, e.g. "Service Started", "Service Stopped", "Connected to Xyz", and maybe even "Schedule Initiated", "User Logged On", etc.
In some cases you may want to make writing to the event log a built-in part of your application and not via the trace system (i.e. write Event Log entries directly). This means it can't accidentally be turned off. (Note you still also want to note the same event in your trace system so you can correlate).
In contrast, a Windows GUI application would generally report these to the user (although they may also log to the Windows Event Log).
Events may also have related performance counters (e.g. number of errors/sec), and it can be important to co-ordinate any direct writing to the Event Log, performance counters, writing to the trace system and reporting to the user so they occur at the same time.
i.e. If a user sees an error message at a particular time, you should be able to find the same error message in the Windows Event Log, and then the same event with the same timestamp in the trace log (along with other trace details).
(2) Activities - Application Log files or database table (and trace files)
This is the regular activity that a system does, e.g. web page served, stock market trade lodged, order taken, calculation performed, etc.
Activity Tracing (start, stop, etc) is useful here (at the right granuality).
Also, it is very common to use a specific Application Log (sometimes called an Audit Log). Usually this is a database table or an application log file and contains structured data (i.e. a set of fields).
Things can get a bit blurred here depending on your application. A good example might be a web server which writes each request to a web log; similar examples might be a messaging system or calculation system where each operation is logged along with application-specific details.
A not so good example is stock market trades or a sales ordering system. In these systems you are probably already logging the activity as they have important business value, however the principal of correlating them to other actions is still important.
As well as custom application logs, activities also often have related peformance counters, e.g. number of transactions per second.
In generally you should co-ordinate logging of activities across different systems, i.e. write to your application log at the same time as you increase your performance counter and log to your trace system. If you do all at the same time (or straight after each other in the code), then debugging problems is easier (than if they all occur at diffent times/locations in the code).
(3) Debug Trace - Text file, or maybe XML or database.
This is information at Verbose level and lower (e.g. custom boolean switches to turn on/off raw data dumps). This provides the guts or details of what a system is doing at a sub-activity level.
This is the level you want to be able to turn on/off for individual sections of your application (hence the multiple sources). You don't want this stuff cluttering up the Windows Event Log. Sometimes a database is used, but more likely are rolling log files that are purged after a certain time.
A big difference between this information and an Application Log file is that it is unstructured. Whilst an Application Log may have fields for To, From, Amount, etc., Verbose debug traces may be whatever a programmer puts in, e.g. "checking values X={value}, Y=false", or random comments/markers like "Done it, trying again".
One important practice is to make sure things you put in application log files or the Windows Event Log also get logged to the trace system with the same details (e.g. timestamp). This allows you to then correlate the different logs when investigating.
If you are planning to use a particular log viewer because you have complex correlation, e.g. the Service Trace Viewer, then you need to use an appropriate format i.e. XML. Otherwise, a simple text file is usually good enough -- at the lower levels the information is largely unstructured, so you might find dumps of arrays, stack dumps, etc. Provided you can correlated back to more structured logs at higher levels, things should be okay.
Q: If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?
A: For files, generally you want rolling log files from a manageability point of view (with System.Diagnostics simply use VisualBasic.Logging.FileLogTraceListener).
Availability again depends on the system. If you are only talking about files then for a server/service, rolling files can just be accessed when necessary. (Windows Event Log or Database Application Logs would have their own access mechanisms).
If you don't have easy access to the file system, then debug tracing to a database may be easier. [i.e. implement a database TraceListener].
One interesting solution I saw for a Windows GUI application was that it logged very detailed tracing information to a "flight recorder" whilst running and then when you shut it down if it had no problems then it simply deleted the file.
If, however it crashed or encountered a problem then the file was not deleted. Either if it catches the error, or the next time it runs it will notice the file, and then it can take action, e.g. compress it (e.g. 7zip) and email it or otherwise make available.
Many systems these days incorporate automated reporting of failures to a central server (after checking with users, e.g. for privacy reasons).
Q: What tools to you use for viewing the logs?
A: If you have multiple logs for different reasons then you will use multiple viewers.
Notepad/vi/Notepad++ or any other text editor is the basic for plain text logs.
If you have complex operations, e.g. activities with transfers, then you would, obviously, use a specialized tool like the Service Trace Viewer. (But if you don't need it, then a text editor is easier).
As I generally log high level information to the Windows Event Log, then it provides a quick way to get an overview, in a structured manner (look for the pretty error/warning icons). You only need to start hunting through text files if there is not enough in the log, although at least the log gives you a starting point. (At this point, making sure your logs have co-ordinated entires becomes useful).
Generally the Windows Event Log also makes these significant events available to monitoring tools like MOM or OpenView.
Others --
If you log to a Database it can be easy to filter and sort informatio (e.g. zoom in on a particular activity id. (With text files you can use Grep/PowerShell or similar to filter on the partiular GUID you want)
MS Excel (or another spreadsheet program). This can be useful for analysing structured or semi-structured information if you can import it with the right delimiters so that different values go in different columns.
When running a service in debug/test I usually host it in a console application for simplicity I find a colored console logger useful (e.g. red for errors, yellow for warnings, etc). You need to implement a custom trace listener.
Note that the framework does not include a colored console logger or a database logger so, right now, you would need to write these if you need them (it's not too hard).
It really annoys me that several frameworks (log4net, EntLib, etc) have wasted time re-inventing the wheel and re-implemented basic logging, filtering, and logging to text files, the Windows Event Log, and XML files, each in their own different way (log statements are different in each); each has then implemented their own version of, for example, a database logger, when most of that already existed and all that was needed was a couple more trace listeners for System.Diagnostics. Talk about a big waste of duplicate effort.
Q: If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?
These things can be turned on/off as needed. I find Trace.axd quite useful for debugging how a server responds to certain things, but it's not generally useful in a heavily used environment or for long term tracing.
Q: What about custom performance counters?
For a professional application, especially a server/service, I expect to see it fully instrumented with both Performance Monitor counters and logging to the Windows Event Log. These are the standard tools in Windows and should be used.
You need to make sure you include installers for the performance counters and event logs that you use; these should be created at installation time (when installing as administrator). When your application is running normally it should not need have administration privileges (and so won't be able to create missing logs).
This is a good reason to practice developing as a non-administrator (have a separate admin account for when you need to install services, etc). If writing to the Event Log, .NET will automatically create a missing log the first time you write to it; if you develop as a non-admin you will catch this early and avoid a nasty surprise when a customer installs your system and then can't use it because they aren't running as administrator.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
combine https://stackoverflow.com/a/51837876/1078784 and answers in this question, I think the best answer is:
cat {SQL FILE NAME} | docker exec -i {MYSQL CONTAINER NAME} {MYSQL PATH IN CONTAINER} --init-command="SET autocommit=0;"
for example in my system this command should look like:
cat temp.sql | docker exec -i mysql.master /bin/mysql --init-command="SET autocommit=0;"
also you can use pv to moniter progress:
cat temp.sql | pv | docker exec -i mysql.master /bin/mysql --init-command="SET autocommit=0;"
And the most important thing here is "--init-command" which will speed up the import progress 10 times fast.
Hi all Please try this property
$( "p span" ).last().addClass( "highlight" );
Thanks
In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"
To see just the symlinks themselves, you can use
find -L /path/to/dir/ -xtype l
while if you want to see also which files they target, just append an ls
find -L /path/to/dir/ -xtype l -exec ls -al {} \;
Stick to php...
Why not only allow the button to appear once an above criteria is met.
<?
if (whatever == something) {
$display = '<input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/>';
return $display;
}
?>
As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.sql.Date.class, ser).create();
This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.
Since you don't mention a plot package , I propose here using Lattice
version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).
## reshaping the data( similar to the other answer)
library(reshape2)
dat.m <- melt(TestData,id.vars='Label')
library(lattice)
bwplot(value~Label |variable, ## see the powerful conditional formula
data=dat.m,
between=list(y=1),
main="Bad or Good")
One cannot disable the browser back button functionality. The only thing that can be done is prevent them.
The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:
<script>
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function() {
null
};
</script>
Suppose there are two pages Page1.php
and Page2.php
and Page1.php
redirects to Page2.php
.
Hence to prevent user from visiting Page1.php
using the back button you will need to place the above script in the head section of Page1.php
.
For more information: Reference
$.ajax("youurl", function(data){
if (data.success == true)
setTimeout(function(){window.location = window.location}, 5000);
})
)
One word answer: asynchronicity.
This topic has been iterated at least a couple of thousands of times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:
@Felix Kling's answer to "How do I return the response from an asynchronous call?". See his excellent answer explaining synchronous and asynchronous flows, as well as the "Restructure code" section.
@Benjamin Gruenbaum has also put a lot of effort explaining asynchronicity in the same thread.
@Matt Esch's answer to "Get data from fs.readFile" also explains asynchronicity extremely well in a simple manner.
Let's trace the common behavior first. In all examples, the outerScopeVar
is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.
Now the question is, when is that callback called?
It depends on the case. Let's try to trace some common behavior again:
img.onload
may be called sometime in the future, when (and if) the image has successfully loaded.setTimeout
may be called sometime in the future, after the delay has expired and the timeout hasn't been canceled by clearTimeout
. Note: even when using 0
as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).$.post
's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.fs.readFile
may be called sometime in the future, when the file has been read successfully or thrown an error.In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.
Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.
More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.
That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:
In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?
It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alert
s and console.log
s too inside the callback function would output the expected result, because the result is available at that point.
Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:
var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);
function helloCatAsync() {
setTimeout(function() {
outerScopeVar = 'Nya';
}, Math.random() * 2000);
}
Note: I'm using setTimeout
with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile
, onload
and any other asynchronous flow.
This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.
Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar
which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):
// 1. Call helloCatAsync passing a callback function,
// which will be called receiving the result from the async operation
helloCatAsync(function(result) {
// 5. Received the result from the async function,
// now do whatever you want with it:
alert(result);
});
// 2. The "callback" parameter is a reference to the function which
// was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
// 3. Start async operation:
setTimeout(function() {
// 4. Finished async operation,
// call the callback passing the result as argument
callback('Nya');
}, Math.random() * 2000);
}
Code snippet of the above example:
// 1. Call helloCatAsync passing a callback function,_x000D_
// which will be called receiving the result from the async operation_x000D_
console.log("1. function called...")_x000D_
helloCatAsync(function(result) {_x000D_
// 5. Received the result from the async function,_x000D_
// now do whatever you want with it:_x000D_
console.log("5. result is: ", result);_x000D_
});_x000D_
_x000D_
// 2. The "callback" parameter is a reference to the function which_x000D_
// was passed as argument from the helloCatAsync call_x000D_
function helloCatAsync(callback) {_x000D_
console.log("2. callback here is the function passed as argument above...")_x000D_
// 3. Start async operation:_x000D_
setTimeout(function() {_x000D_
console.log("3. start async operation...")_x000D_
console.log("4. finished async operation, calling the callback, passing the result...")_x000D_
// 4. Finished async operation,_x000D_
// call the callback passing the result as argument_x000D_
callback('Nya');_x000D_
}, Math.random() * 2000);_x000D_
}
_x000D_
Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync
implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.
You will also notice that due to the asynchronous nature, it is impossible to return
a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.
Instead of return
ing a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.
Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).
Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:
Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.
I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!
You can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.
EDIT:
If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.
The solution is already answered here above (long ago).
But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).
This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.
I have used this simple code, and it works!
for (int i = 0; i < N * N; i++)
{
Thread.Sleep(50);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
(float)10.25, FontStyle.Bold),
Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
}
It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#
I used this code, and it does work.
I've approached this in a different way. I've created a function which simply returns true or false.. Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function
Step 1
yarn add esm
or
npm i esm --save
Step 2
package.json
"scripts": {
"start": "node -r esm src/index.js",
}
Step 3
nodemon --exec npm start
You must use one of the following ways:
string s = @"loooooooooooooooooooooooong loooooong
long long long";
string s = "loooooooooong loooong" +
" long long" ;
In terms of speed: #1 and #4, but not by much in most instances.
You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_
is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)
#5 might be similar.
In terms memory usage: They're all the same except for #5.
for (@a)
is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.
In terms of readability: #1.
In terms of flexibility: #1/#4 and #5.
#2 does not support elements that are false. #2 and #3 are destructive.
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
"12345".each_char.map(&:to_i)
each_char
does basically the same as split('')
: It splits a string into an array of its characters.
hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..
The simplest fix is to make the comparator function be static:
static int comparator (const Bar & first, const Bar & second);
^^^^^^
When invoking it in Count
, its name will be Foo::comparator
.
The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo
.
Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo
.
ingconti is right.
www.dropbox.com
with dl.dropboxusercontent.com
in the link, like https://dl.dropboxusercontent.com/s/qgknrfngaxazm38/app.plistdownload.html
file with a link formatted as <a href="itms-services://?action=download-manifest&url=https://dl.dropboxusercontent.com/s/qgknrfngaxazm38/app.plist">INSTALL!!</a>
download.html
to dropboxwww.dropbox.com
with dl.dropboxusercontent.com
in the second link as well, like https://dl.dropboxusercontent.com/s/gnoctp7n9g0l3hx/download.htmlNow, visit https://dl.dropboxusercontent.com/s/gnoctp7n9g0l3hx/download.html
in your device, you can install the app like before.
WHAT A WONDERFUL WORLD!
You can get all post data into this function :-
$postData = $request->post();
and if you want specific filed then use it :-
$request->post('current-password');
Try this:
DECLARE @COMBINED_STRINGS AS VARCHAR(50); -- Allocate just enough length for the two strings.
SET @COMBINED_STRINGS = 'rupesh''s' + 'malviya';
SELECT @COMBINED_STRINGS; -- Print your combined strings.
Or you can put your strings into variables. Such that:
DECLARE @COMBINED_STRINGS AS VARCHAR(50),
@STRING1 AS VARCHAR(20),
@STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SELECT @COMBINED_STRINGS;
Output:
rupesh'smalviya
Just add a space in your string as a separator.
My way is importing the jquery library.
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>