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()
I just improve the groovy script from above to write the property in the root parent properties file:
import java.io.*;
String p = project.properties['env-properties-file']
File f = new File(p)
if (f.exists()) {
try{
FileWriter fstream = new FileWriter(f.getAbsolutePath())
BufferedWriter out = new BufferedWriter(fstream)
String propToSet = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator))
if (File.separator != "/") {
propToSet = propToSet.replace(File.separator,File.separator+File.separator+File.separator)
}
out.write("jacoco.agent = " + propToSet + "/lib/jacocoagent.jar")
out.close()
}catch (Exception e){
}
}
String ret = "../"
while (!f.exists()) {
f = new File(ret + p)
ret+= "../"
}
project.properties['env-properties-file-by-groovy'] = f.getAbsolutePath()
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions
:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
JavaScript can't connect directly to DB to get needed data but you can use AJAX. To make easy AJAX request to server you can use jQuery JS framework http://jquery.com. Here is a small example
JS:
jQuery.ajax({
type: "GET",
dataType: "json",
url: '/ajax/usergroups/filters.php',
data: "controller=" + controller + "&view=" + view,
success: function(json)
{
alert(json.first);
alert(json.second);
});
PHP:
$out = array();
// mysql connection and select query
$conn = new mysqli($servername, $username, $password, $dbname);
try {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM [table_name] WHERE condition = [conditions]";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$out[] = [
'field1' => $row["field1"],
'field2' => $row["field2"]
];
}
} else {
echo "0 results";
}
} catch(Exception $e) {
echo "Error: " . $e->getMessage();
}
echo json_encode($out);
Robert Rossney has a good solution. Here's an alternative solution I've used in the past that separates out the "Overlay" from the rest of the content. This solution takes advantage of the attached property Panel.ZIndex
to place the "Overlay" on top of everything else. You can either set the Visibility of the "Overlay" in code or use a DataTrigger
.
<Grid x:Name="LayoutRoot">
<Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity=".5"/>
</Grid.Background>
<!-- Add controls as needed -->
</Grid>
<!-- Use whatever layout you need -->
<ContentControl x:Name="MainContent" />
</Grid>
There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments
I prefer using HTTP Headers for this kind of contextual information.
For the total number of elements, I use the X-total-count
header.
For links to next, previous page, etc. I use HTTP Link
header:
http://www.w3.org/wiki/LinkHeader
Github does it the same way: https://developer.github.com/v3/#pagination
In my opinion, it's cleaner since it can be used also when you return content that doesn't support hyperlinks (i.e binaries, pictures).
I have decompiled Google Play services revision 14 library. I think there is a bug in com.google.android.gms.common.GooglePlayServicesUtil.class
. The aforementioned string appears only in one place:
public static int isGooglePlayServicesAvailable(Context context) {
PackageManager localPackageManager = context.getPackageManager();
try {
Resources localResources = context.getResources();
localResources.getString(R.string.common_google_play_services_unknown_issue);
} catch (Throwable localThrowable1) {
Log.e("GooglePlayServicesUtil", "The Google Play services resources were not found. "
+ "Check your project configuration to ensure that the resources are included.");
}
....
There is no R.class
in com.google.android.gms.common
package.
There is an import com.google.android.gms.R.string;
, but no usage of string.something
, so I guess this is the error - there should be import com.google.android.gms.R;
.
Nevertheless the isGooglePlayServicesAvailable
method works as intended (except of logging that warning), but there are other methods in that class, which uses unimported R.class
, so there may be some other errors. Although banners in my application works fine...
For windows, you need to download the latest version of the open SSL binaries at this time is:
openssl-1.0.2k-x64_86-win64.zip
this problem happened to me when I tried to run MongoDB bin in windows 10
source to download: https://indy.fulgan.com/SSL/
Please note this doesn't solve the cookie sharing process, as in general this is bad practice.
You need to be using JSONP as your type:
From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
$.ajax(
{
type: "POST",
url: "http://example.com/api/getlist.json",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
},
success: function(){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
}
);
I don't know if this is new functionality, but this will plot on separate figures:
df.plot(y='korisnika')
df.plot(y='osiguranika')
while this will plot on the same figure: (just like the code in the op)
df.plot(y=['korisnika','osiguranika'])
I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.
The syntax is almost the same as printf
. With printf
you give the string format and its contents ie:
printf("my %s has %d chars\n", "string format", 30);
With fprintf
it is the same, except now you are also specifying the place to print to:
File *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);
Or in your case:
fprintf( stderr, "my %s has %d chars\n", "string format", 30);
But from what I see you have quite a simple error in syntax
<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>
the correct syntax would look like
<p th:text="${bean.field + '!' + bean.field}">Static content</p>
As a matter of fact, the syntax th:text="'static part' + ${bean.field}"
is equal to th:text="${'static part' + bean.field}"
.
Try it out. Even though this is probably kind of useless now after 6 months.
Reflector and its add-in FileDisassembler.
Reflector will allow to see the source code. FileDisassembler will allow you to convert it into a VS solution.
The second sample assigns a unique ID to the element in question. This element can then be manipulated or accessed using DHTML.
The first one, on the other hand, sets a named location within the document, akin to a bookmark. Attached to an "anchor", it makes perfect sense.
The for
-in
loops for each property in an object or array. You can use this property to get to the value as well as change it.
Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.
For in looks like:
for (var property in object) loop();
Some sample code:
function xinspect(o,i){
if(typeof i=='undefined')i='';
if(i.length>50)return '[MAX ITERATIONS]';
var r=[];
for(var p in o){
var t=typeof o[p];
r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+' ') : o[p]+''));
}
return r.join(i+'\n');
}
// example of use:
alert(xinspect(document));
Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.
Edit 2: Well, I wrote one up anyway.
You can wrap them in a div and give the div a set width (the width of the widest image + margin maybe?) and then float the divs. Then, set the images to the center of their containing divs. Your margins between images won't be consistent for the differently sized images but it'll lay out much more nicely on the page.
Another way is shown in this CodeProject article:
http://www.codeproject.com/KB/IP/tswindowclipper.aspx
The basic idea is to create a virutal channel that sends the windows position of the app(s) you want to show, then only render that part of the window on the client.
If you are in the iframe context,
you could do
const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);
If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is
document.getElementById("iframe_id").contentWindow.location.href
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
You have to reformat the string as well as converting to the correct time. In this case I needed Zulu time.
Declare @Date datetime;
Declare @DateString varchar(50);
set @Date = GETDATE();
declare @ZuluTime datetime;
Declare @DateFrom varchar (50);
Declare @DateTo varchar (50);
set @ZuluTime = DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @Date);
set @DateString = FORMAT(@ZuluTime, 'yyyy-MM-ddThh:mm:ssZ', 'en-US' )
select @DateString;
Here what you can try:
var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds
hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.
//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);
I dont know if that is the most elegant way, but it now works for me.
I add that code before this one on line 13 or something
// Find out the index for the last value in our path array
$last = end(array_keys($path));
Adding data-dismiss="modal"
on any buttons in my modal worked for me. I wanted my button to call a function with angular to fire an ajax call AND close the modal so I added a .toggle()
within the function and it worked well. (In my case I used a bootstrap modal
and used some angular
, not an actual modal controller).
<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="functionName()"> Do Something </button>
$scope.functionName = function () {
angular.element('#modalId').toggle();
$.ajax({ ajax call })
}
Maybe:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
Like most things "it depends". It's not right or wrong/good or bad in and of itself to store data in columns or JSON. It depends on what you need to do with it later. What is your predicted way of accessing this data? Will you need to cross reference other data?
Other people have answered pretty well what the technical trade-off are.
Not many people have discussed that your app and features evolve over time and how this data storage decision impacts your team.
Because one of the temptations of using JSON is to avoid migrating schema and so if the team is not disciplined, it's very easy to stick yet another key/value pair into a JSON field. There's no migration for it, no one remembers what it's for. There is no validation on it.
My team used JSON along side traditional columns in postgres and at first it was the best thing since sliced bread. JSON was attractive and powerful, until one day we realized that flexibility came at a cost and it's suddenly a real pain point. Sometimes that point creeps up really quickly and then it becomes hard to change because we've built so many other things on top of this design decision.
Overtime, adding new features, having the data in JSON led to more complicated looking queries than what might have been added if we stuck to traditional columns. So then we started fishing certain key values back out into columns so that we could make joins and make comparisons between values. Bad idea. Now we had duplication. A new developer would come on board and be confused? Which is the value I should be saving back into? The JSON one or the column?
The JSON fields became junk drawers for little pieces of this and that. No data validation on the database level, no consistency or integrity between documents. That pushed all that responsibility into the app instead of getting hard type and constraint checking from traditional columns.
Looking back, JSON allowed us to iterate very quickly and get something out the door. It was great. However after we reached a certain team size it's flexibility also allowed us to hang ourselves with a long rope of technical debt which then slowed down subsequent feature evolution progress. Use with caution.
Think long and hard about what the nature of your data is. It's the foundation of your app. How will the data be used over time. And how is it likely TO CHANGE?
There is two condition,
So, For that purpose, you have to follow this steps:
Go to Build Settings and perform below steps with search,
After that, clean and rebuild your project.
In that case,First write "@objc" before your class in swift file.
After that ,In your objective c file, write this,
#import "YourProjectName-Swift.h"
In that case, In your header file, write this,
#import "YourObjective-c_FileName.h"
I hope this will help you.
A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2]
, the code right now would scale that to have intensities of [0, 128, 255]
. You want these to remain small after converting to np.uint8
.
Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo
and provide it the type (dtype
) of the image and you will obtain a structure of information for that type. You would then access the max
field from this structure to determine the maximum value.
So with the above, do the following modifications to your code:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
Note that I've additionally converted the image into np.float64
in case the incoming data type is not so and to maintain floating-point precision when doing the division.
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
I’ve just solved the same problem. I had MinGW with GCC and G++ installed but not make
. This command helped me:
mingw-get.exe install mingw32-make
After running it, clear CMake cache (delete the CMakeCache.txt
file in the CMake's working directory) and run CMake again.
file.readlines()
or file.read().split('\n')
list.insert()
.Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.
Here is the code for this
public void ConvertHtmlToImage()
{
Bitmap m_Bitmap = new Bitmap(400, 600);
PointF point = new PointF(0, 0);
SizeF maxSize = new System.Drawing.SizeF(500, 500);
HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
"<html><body><p>This is some html code</p>"
+ "<p>This is another html line</p></body>",
point, maxSize);
m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}
If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
I just found wdb (http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401). It has a pretty nice user interface / GUI with all the bells and whistles. Author says this about wdb -
"There are IDEs like PyCharm that have their own debuggers. They offer similar or equal set of features ... However to use them you have to use those specific IDEs (and some of then are non-free or may not be available for all platforms). Pick the right tool for your needs."
Thought i'd just pass it on.
Also a very helpful article about python debuggers: https://zapier.com/engineering/debugging-python-boss/
Finally, if you'd like to see a nice graphical printout of your call stack in Django, checkout: https://github.com/joerick/pyinstrument. Just add pyinstrument.middleware.ProfilerMiddleware to MIDDLEWARE_CLASSES, then add ?profile to the end of the request URL to activate the profiler.
Can also run pyinstrument from command line or by importing as a module.
In MonoDroid here's how (c#)
/// <summary>
/// Graphics support for resizing images
/// </summary>
public static class Graphics
{
public static Bitmap ScaleDownBitmap(Bitmap originalImage, float maxImageSize, bool filter)
{
float ratio = Math.Min((float)maxImageSize / originalImage.Width, (float)maxImageSize / originalImage.Height);
int width = (int)Math.Round(ratio * (float)originalImage.Width);
int height =(int) Math.Round(ratio * (float)originalImage.Height);
Bitmap newBitmap = Bitmap.CreateScaledBitmap(originalImage, width, height, filter);
return newBitmap;
}
public static Bitmap ScaleBitmap(Bitmap originalImage, int wantedWidth, int wantedHeight)
{
Bitmap output = Bitmap.CreateBitmap(wantedWidth, wantedHeight, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(output);
Matrix m = new Matrix();
m.SetScale((float)wantedWidth / originalImage.Width, (float)wantedHeight / originalImage.Height);
canvas.DrawBitmap(originalImage, m, new Paint());
return output;
}
}
You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.
In the newer apache poi versions:
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
In addition to the ?ShiftU/CtrlShiftU solution, you can also add a link quickly by doing the following:
I couldn't find it documented anywhere, but it works, and seems very handy.
Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely
and up:
# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely
# Options
$option1 = New-ScheduledJobOption –StartIfIdle
$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"
Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger
I think I have good solution how to fix problem like this - List => List with grouping by Something.a & Something.b. There is extended definition:
public class Test {
public static void test() {
class A {
private int a;
private int b;
private float c;
private float d;
public A(int a, int b, float c, float d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
List<A> list1 = new ArrayList<A>();
list1.addAll(Arrays.asList(new A(1, 2, 3, 4),
new A(2, 3, 4, 5),
new A(1, 2, 3, 4),
new A(2, 3, 4, 5),
new A(1, 2, 3, 4)));
Map<Integer, A> map = list1.stream()
.collect(HashMap::new, (m, v) -> m.put(
Objects.hash(v.a, v.b, v.c, v.d), v),
HashMap::putAll);
list1.clear();
list1.addAll(map.values());
System.out.println(list1);
}
}
class A, list1 it's just incoming data - magic is in the Objects.hash(...) :)
Added content of pg_env.sh to my .bashrc:
cat /opt/PostgreSQL/10/pg_env.sh
#!/bin/sh
# The script sets environment variables helpful for PostgreSQL
export PATH=/opt/PostgreSQL/10/bin:$PATH
export PGDATA=/opt/PostgreSQL/10/data
export PGDATABASE=postgres
export PGUSER=postgres
export PGPORT=5433
export PGLOCALEDIR=/opt/PostgreSQL/10/share/locale
export MANPATH=$MANPATH:/opt/PostgreSQL/10/share/man
with addition of (as per user4653174 suggestion)
export PGPASSWORD='password'
Found this approach on another site. It works with the new larger sizes of Excel and doesn't require you to hardcode the max number of rows and columns.
iLastRow = Cells(Rows.Count, "a").End(xlUp).Row
iLastCol = Cells(i, Columns.Count).End(xlToLeft).Column
Apart from running services(OracleServiceXE,OracleXETNSListener) on there is a chance your Anti-virus software/firewall may still block them. Just make sure they are not blocked.
$("input[@name='<%=test2.ClientID%>']:checked");
use this and here ClientID fetch random id created by .net.
Get position of div in respect to left and Top
var elm = $('#div_id'); //get the div
var posY_top = elm.offset().top; //get the position from top
var posX_left = elm.offset().left; //get the position from left
This sort of approach should work.
var plugin_exists = true;
try {
// some code that requires that plugin here
} catch(err) {
plugin_exists = false;
}
Hi above answer will not work if I want to select one or more column value which is not same or may be same for both row data
For Ex. I want to select username, birth date also. But in database is username is not duplicate but birth date will be duplicate then this solution will not work.
For this use this solution Need to take self join on same table/
SELECT
distinct(p1.id), p1.payer_email , p1.username, p1.birth_date
FROM
paypal_ipn_orders AS p1
INNER JOIN paypal_ipn_orders AS p2
ON p1.payer_email=p2.payer_email
WHERE
p1.birth_date=p2.birth_date
Above query will return all records having same email_id and same birth date
I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.
So, you may get a chance with:
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)
As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.
If you mean how to remove the 'checked' state from all checkboxes:
$('input:checkbox').removeAttr('checked');
The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC
See http://play.golang.org/p/vTidOlmb9P
A nifty non-caching async one liner for node 15 modules:
import { readFile } from 'fs/promises';
const data = await readFile('{{ path }}').then(json => JSON.parse(json)).catch(() => null);
you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number
#!/usr/bin/ruby
first_number = ARGV[0].to_i
second_number = ARGV[1].to_i
puts first_number + second_number
and you call it like this
% ./plus.rb 5 6
==> 11
There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.
If you are testing for file existence you want -e not -L. -L tests for a symlink.
Lets Experiment with below code Playground.I Hope will clear idea what is optional and reason of using it.
var sampleString: String? ///Optional, Possible to be nil
sampleString = nil ////perfactly valid as its optional
sampleString = "some value" //Will hold the value
if let value = sampleString{ /// the sampleString is placed into value with auto force upwraped.
print(value+value) ////Sample String merged into Two
}
sampleString = nil // value is nil and the
if let value = sampleString{
print(value + value) ///Will Not execute and safe for nil checking
}
// print(sampleString! + sampleString!) //this line Will crash as + operator can not add nil
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.
Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.
Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.
Step 1) Add a COM reference in your project to Microsoft HTML Object Library
Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml
Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>
Step 4) Add a WebBrowser control to your project
Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me
Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:
Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
Dim head As HtmlElement
Dim script As HtmlElement
Dim domElement As IHTMLScriptElement
head = wb.Document.GetElementsByTagName("head")(0)
script = wb.Document.CreateElement("script")
domElement = script.DomElement
domElement.type = "text/javascript"
domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
head.AppendChild(script)
End Sub
Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:
Public Sub Callback_GetVar(ByVal vVar As String)
Debug.Print(vVar)
End Sub
Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
End Sub
Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.
To get this i tried following code :
protected T GetObject<T>()
{
T obj = default(T);
obj =Activator.CreateInstance<T>();
return obj ;
}
DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';
SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2
You can group selectors:
#selector1, #selector2, #selector3 { color: black; }
Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...
Put this function into a new module:
Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
On Error Resume Next
x.Interior.Color = RGB(R, G, B)
x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function
Then use this formula in your sheet, for example in cell D2
:
=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")
Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2
to C2
. The font color is a contrasting white or black.
Without actual data it is hard to answer the question but I guess you are looking for something like this:
Top15['Citable docs per Capita'].corr(Top15['Energy Supply per Capita'])
That calculates the correlation between your two columns 'Citable docs per Capita'
and 'Energy Supply per Capita'
.
To give an example:
import pandas as pd
df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})
A B
0 0 0
1 1 2
2 2 4
3 3 6
Then
df['A'].corr(df['B'])
gives 1
as expected.
Now, if you change a value, e.g.
df.loc[2, 'B'] = 4.5
A B
0 0 0.0
1 1 2.0
2 2 4.5
3 3 6.0
the command
df['A'].corr(df['B'])
returns
0.99586
which is still close to 1, as expected.
If you apply .corr
directly to your dataframe, it will return all pairwise correlations between your columns; that's why you then observe 1s
at the diagonal of your matrix (each column is perfectly correlated with itself).
df.corr()
will therefore return
A B
A 1.000000 0.995862
B 0.995862 1.000000
In the graphic you show, only the upper left corner of the correlation matrix is represented (I assume).
There can be cases, where you get NaN
s in your solution - check this post for an example.
If you want to filter entries above/below a certain threshold, you can check this question. If you want to plot a heatmap of the correlation coefficients, you can check this answer and if you then run into the issue with overlapping axis-labels check the following post.
This is my answer
#include<stdio.h>
int main()
{int mat[100][100];
int row,column,i,j;
printf("enter how many row and colmn you want:\n \n");
scanf("%d",&row);
scanf("%d",&column);
printf("enter the matrix:");
for(i=0;i<row;i++){
for(j=0;j<column;j++){
scanf("%d",&mat[i][j]);
}
printf("\n");
}
for(i=0;i<row;i++){
for(j=0;j<column;j++){
printf("%d \t",mat[i][j]);}
printf("\n");}
}
I just choose an approximate value for the row and column. My selected row or column will not cross the value.and then I scan the matrix element then make it in matrix size.
If you want an index, you can use std::find
in combination with std::distance
.
auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
// name not in vector
} else
{
auto index = std::distance(Names.begin(), it);
}
Yes, you can install multiple versions of Xcode. They will install into separate directories. I've found that the best practice is to install the version that came with your Mac first and then install downloaded versions, but it probably doesn't make a big difference. See http://developer.apple.com/documentation/Xcode/Conceptual/XcodeCoexistence/Contents/Resources/en.lproj/Details/Details.html this Apple Developer Connection page for lots of details. <- Page does not exist anymore!
Java8 +
import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)
None of those worked for me in Chrome 42...
Instead my directive now uses this link
function (base64
made it work):
link: function(scope, element, attrs) {
var downloadFile = function downloadFile() {
var filename = scope.getFilename();
var link = angular.element('<a/>');
link.attr({
href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(scope.csv)),
target: '_blank',
download: filename
})[0].click();
$timeout(function(){
link.remove();
}, 50);
};
element.bind('click', function(e) {
scope.buildCSV().then(function(csv) {
downloadFile();
});
scope.$apply();
});
}
Use This [Tested]
To get numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values
To get non-numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
You may try it like this:
DECLARE @i int = 0
WHILE @i < 300
BEGIN
SET @i = @i + 1
/* your code*/
END
This is the solution for Node.js which is asynchronous.
using the async npm package.
(JavaScript) Synchronizing forEach Loop with callbacks inside
This is another sample. Which basically works for user-defined pattern.
public static LinkedHashMap<String, Object> checkDateDiff(DateTimeFormatter dtfObj, String startDate, String endDate)
{
Map<String, Object> dateDiffMap = new HashMap<String, Object>();
DateTime start = DateTime.parse(startDate,dtfObj);
DateTime end = DateTime.parse(endDate,dtfObj);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
dateDiffMap.put("ISO-8601_PERIOD_FORMAT", period);
dateDiffMap.put("YEAR", period.getYears());
dateDiffMap.put("MONTH", period.getMonths());
dateDiffMap.put("WEEK", period.getWeeks());
dateDiffMap.put("DAY", period.getWeeks());
dateDiffMap.put("HOUR", period.getHours());
dateDiffMap.put("MINUTE", period.getMinutes());
dateDiffMap.put("SECOND", period.getSeconds());
return dateDiffMap;
}
There is no reason not to use C <stdio.h>
in C++, and in fact it is often the optimal choice.
#include <stdio.h>
int
main() // (void) not necessary in C++
{
int c;
while ((c = getchar()) != EOF) {
// do something with 'c' here
}
return 0; // technically not necessary in C++ but still good style
}
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
Writing your own library is not that hard as u might thing. Here is link for Shunting-yard algorithm with step by step algorithm explenation. Although, you will have to parse the input for tokens first.
There are 2 other questions wich can give you some information too: Turn a String into a Math Expression? What's a good library for parsing mathematical expressions in java?
It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!
Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:
switch (<condition>) {
case c_0: ...
case c_1: ...
...
case c_n: ...
default: ...
}
where c_0
, c_1
, ..., and c_N
are integral numbers that are targets of the switch statement, and <condition>
must resolve to an integer expression.
If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k
is larger than some empirical value, a jump table can be generated, which is highly efficient.
If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.
For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.
Finally, of course, if the domain of <condition>
is not the integers, a switch
statement is completely useless.
Since Google updates sometimes the name of fixed object properties, the best practice is to use GMaps V3 methods to get coordinates event.overlay.getPath().getArray() and to get lat latlng.lat() and lng latlng.lng().
So, I just wanted to improve this answer a bit exemplifying with polygon and POSTGIS insert case scenario:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var str_input ='POLYGON((';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
console.log('polygon path array', event.overlay.getPath().getArray());
$.each(event.overlay.getPath().getArray(), function(key, latlng){
var lat = latlng.lat();
var lon = latlng.lng();
console.log(lat, lon);
str_input += lat +' '+ lon +',';
});
}
str_input = str_input.substr(0,str_input.length-1) + '))';
console.log('the str_input will be:', str_input);
// YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
// INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')
});
The following is about plain C functions - in a C++ class the modifier 'static' has another meaning.
If you have just one file, this modifier makes absolutely no difference. The difference comes in bigger projects with multiple files:
In C, every "module" (a combination of sample.c and sample.h) is compiled independently and afterwards every of those compiled object files (sample.o) are linked together to an executable file by the linker.
Let's say you have several files that you include in your main file and two of them have a function that is only used internally for convenience called add(int a, b)
- the compiler would easily create object files for those two modules, but the linker will throw an error, because it finds two functions with the same name and it does not know which one it should use (even if there's nothing to link, because they aren't used somewhere else but in it's own file).
This is why you make this function, which is only used internal, a static function. In this case the compiler does not create the typical "you can link this thing"-flag for the linker, so that the linker does not see this function and will not generate an error.
Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).
An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:
new Promise((resolve, reject) => {
setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
_x000D_
The above could would not be possible to write with throw.
try{
new Promise((resolve, reject) => {
setTimeout(()=>{throw new Error('err msg')}, 1000);
return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
}catch(o){
console.log("IGNORED", o)
}
_x000D_
In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.
First, thanks for the answers above! They lead to my solution.
I added this alias to my .bashrc file:
alias now='date +%Y-%m-%d-%H.%M.%S'
Now when I want to put a time stamp on a file such as a build log I can do this:
mvn clean install | tee build-$(now).log
and I get a file name like:
build-2021-02-04-03.12.12.log
AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.
This is a useful function for quick and easy xml parsing when an extension is not available:
<?php
/**
* Convert XML to an Array
*
* @param string $XML
* @return array
*/
function XMLtoArray($XML)
{
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $XML, $vals);
xml_parser_free($xml_parser);
// wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
$_tmp='';
foreach ($vals as $xml_elem) {
$x_tag=$xml_elem['tag'];
$x_level=$xml_elem['level'];
$x_type=$xml_elem['type'];
if ($x_level!=1 && $x_type == 'close') {
if (isset($multi_key[$x_tag][$x_level]))
$multi_key[$x_tag][$x_level]=1;
else
$multi_key[$x_tag][$x_level]=0;
}
if ($x_level!=1 && $x_type == 'complete') {
if ($_tmp==$x_tag)
$multi_key[$x_tag][$x_level]=1;
$_tmp=$x_tag;
}
}
// jedziemy po tablicy
foreach ($vals as $xml_elem) {
$x_tag=$xml_elem['tag'];
$x_level=$xml_elem['level'];
$x_type=$xml_elem['type'];
if ($x_type == 'open')
$level[$x_level] = $x_tag;
$start_level = 1;
$php_stmt = '$xml_array';
if ($x_type=='close' && $x_level!=1)
$multi_key[$x_tag][$x_level]++;
while ($start_level < $x_level) {
$php_stmt .= '[$level['.$start_level.']]';
if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
$php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
$start_level++;
}
$add='';
if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
if (!isset($multi_key2[$x_tag][$x_level]))
$multi_key2[$x_tag][$x_level]=0;
else
$multi_key2[$x_tag][$x_level]++;
$add='['.$multi_key2[$x_tag][$x_level].']';
}
if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
if ($x_type == 'open')
$php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
else
$php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
eval($php_stmt_main);
}
if (array_key_exists('attributes', $xml_elem)) {
if (isset($xml_elem['value'])) {
$php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
eval($php_stmt_main);
}
foreach ($xml_elem['attributes'] as $key=>$value) {
$php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
eval($php_stmt_att);
}
}
}
return $xml_array;
}
?>
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
Inspired by this post and by the Stack Overflow question that led me here -- Is it possible to insert multiple rows at a time in an SQLite database? -- I've posted my first Git repository:
https://github.com/rdpoor/CreateOrUpdate
which bulk loads an array of ActiveRecords into MySQL, SQLite or PostgreSQL databases. It includes an option to ignore existing records, overwrite them or raise an error. My rudimentary benchmarks show a 10x speed improvement compared to sequential writes -- YMMV.
I'm using it in production code where I frequently need to import large datasets, and I'm pretty happy with it.
ArrayList
is unique in its naming standards. Here are the equivalencies:
Array.push -> ArrayList.add(Object o); // Append the list
Array.pop -> ArrayList.remove(int index); // Remove list[index]
Array.shift -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list
Note that unshift
does not remove an element, but instead adds one to the list. Also note that corner-case behaviors are likely to be different between Java and JS, since they each have their own standards.
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.
As I recognize, at the moment, in JUnit, the syntax is like this:
AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");
Means that, the condition is in front of the message.
You will find complete list of time zone with its GMToffsets
here and you can use "Name of Time Zone" column value to find time zone by ID
e.g
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindTimeZoneById("Dateline Standard Time");
You will get time zone info class that contains dateline standard time time zone which is used for GMT-12:00.
For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click()
function as the first parameter, followed by the event handler function.
Here's some code to illustrate what I mean:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
The correct fix is to add the property in the type definition as explained in @Nitzan Tomer's answer. If that's not an option though:
You can assign the object to a constant of type any, then call the 'non-existing' property.
const newObj: any = oldObj;
return newObj.someProperty;
You can also cast it as any
:
return (oldObj as any).someProperty;
This fails to provide any type safety though, which is the point of TypeScript.
Another thing you may consider, if you're unable to modify the original type, is extending the type like so:
interface NewType extends OldType {
someProperty: string;
}
Now you can cast your variable as this NewType
instead of any
. Still not ideal but less permissive than any
, giving you more type safety.
return (oldObj as NewType).someProperty;
If you are using SQL Server 2005 the following will work:
select *
from sys.procedures
where is_ms_shipped = 0
<style>
a:hover {
cursor:pointer;
}
</style>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
var href = $(this).attr("href").split("#");
$(".results").text(href[1]);
})
})
</script>
<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>
<br /><br />
<div class="results"></div>
Use sed:
MYVAR=ho02123ware38384you443d34o3434ingtod38384day
echo "$MYVAR" | sed -e 's/[a-zA-Z]/X/g' -e 's/[0-9]/N/g'
# prints XXNNNNNXXXXNNNNNXXXNNNXNNXNNNNXXXXXXNNNNNXXX
Note that the subsequent -e
's are processed in order. Also, the g
flag for the expression will match all occurrences in the input.
You can also pick your favorite tool using this method, i.e. perl, awk, e.g.:
echo "$MYVAR" | perl -pe 's/[a-zA-Z]/X/g and s/[0-9]/N/g'
This may allow you to do more creative matches... For example, in the snip above, the numeric replacement would not be used unless there was a match on the first expression (due to lazy and
evaluation). And of course, you have the full language support of Perl to do your bidding...
You can just create a new branch and switch onto it. Commit your changes then:
git branch dirty
git checkout dirty
// And your commit follows ...
Alternatively, you can also checkout an existing branch (just git checkout <name>
). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.
My gut told me the same thing when I came across this design.
I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.
I would ask the question "just because you can, should you?"
See this article for the problem I came across related to this design.
The specified LINQ expression contains references to queries that are associated with different contexts
From http://www.faqs.org/docs/diveintopython/fileinfo_private.html
Strictly speaking, private methods are accessible outside their class, just not easily accessible. Nothing in Python is truly private; internally, the names of private methods and attributes are mangled and unmangled on the fly to make them seem inaccessible by their given names. You can access the __parse method of the MP3FileInfo class by the name _MP3FileInfo__parse. Acknowledge that this is interesting, then promise to never, ever do it in real code. Private methods are private for a reason, but like many other things in Python, their privateness is ultimately a matter of convention, not force.
Hell?, I am a compiler.
I just scanned thousands of lines of code while you were reading this sentence. I browsed through millions of possibilities of optimizing a single line of yours using hundreds of different optimization techniques based on a vast amount of academic research that you would spend years getting at. I won't feel any embarrassment, not even a slight ick, when I convert a three-line loop to thousands of instructions just to make it faster. I have no shame to go to great lengths of optimization or to do the dirtiest tricks. And if you don't want me to, maybe for a day or two, I'll behave and do it the way you like. I can transform the methods I'm using whenever you want, without even changing a single line of your code. I can even show you how your code would look in assembly, on different processor architectures and different operating systems and in different assembly conventions if you'd like. Yes, all in seconds. Because, you know, I can; and you know, you can't.
P.S. Oh, by the way you weren't using half of the code you wrote. I did you a favor and threw it away.
http://www.decompileandroid.com/
This website will decompile the code embedded in APK files and extract all the other assets in the file.
Here is another use case which worked well for me.
Code: Swift 5.3
// Assuming you have a view named "targeView"
scrollView.scroll(to: CGPoint(x:targeView.frame.minX, y:targeView.frame.minY), animated: true)
As you can guess if you want to scroll to make a bottom part of your target view visible then use maxX and minY.
The python manual provides the following:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", repr(c)
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
which can be rolled into your use case.
Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-
We are doing AND operation in this example. There are also other masking operators- OR, XOR.
Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-
1 1 1 0 1 1 0 1 [input] (&) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 0 0 1 0 1 1 0 0 [output]
So, only the middle 4 bits (as these bits are 1
in this mask) remain.
Lets see this with XOR-
1 1 1 0 1 1 0 1 [input] (^) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 1 1 0 1 0 0 0 1 [output]
Now, the middle 4 bits are flipped (1
became 0
, 0
became 1
).
So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-
bool isOdd(int i) {
return i%2;
}
This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-
bool isOdd(int i) {
return i&1;
}
Short Explanation: If the least significant bit of a binary number is 1
then it is odd; for 0
it will be even. So, by doing AND with 1
we are removing all other bits except for the least significant bit i.e.:
55 -> 0 0 1 1 0 1 1 1 [input] (&) 1 -> 0 0 0 0 0 0 0 1 [mask] --------------------------------------- 1 <- 0 0 0 0 0 0 0 1 [output]
If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work
hive> select cast('2147483647' as int);
OK
2147483647
hive> select cast('2147483648' as int);
OK
NULL
hive> select cast('2147483648' as bigint);
OK
2147483648
Minimal example varying azim
, dist
and elev
To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245
Here is my test program:
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
if len(sys.argv) > 1:
azim = int(sys.argv[1])
else:
azim = None
if len(sys.argv) > 2:
dist = int(sys.argv[2])
else:
dist = None
if len(sys.argv) > 3:
elev = int(sys.argv[3])
else:
elev = None
# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)
# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
if azim is not None:
ax.azim = azim
if dist is not None:
ax.dist = dist
if elev is not None:
ax.elev = elev
print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))
plt.savefig(
'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
format='png',
bbox_inches='tight'
)
Running it without arguments gives the default values:
ax.azim = -60
ax.dist = 10
ax.elev = 30
main_-60_10_30.png
Vary azim
The azimuth is the rotation around the z axis e.g.:
main_-60_10_30.png
main_0_10_30.png
main_60_10_30.png
Vary dist
dist
seems to be the distance from the center visible point in data coordinates.
main_-60_10_30.png
main_-60_5_30.png
main_-60_20_-30.png
Vary elev
From this we understand that elev
is the angle between the eye and the xy plane.
main_-60_10_60.png
main_-60_10_30.png
main_-60_10_0.png
main_-60_10_-30.png
Tested on matpotlib==3.2.2.
Use
[self dismissViewControllerAnimated:NO completion:nil];
In my case, all other solutions didn't work, but this one did:
obj = {...arr}
my arr is in a form: [name: "the name", email: "[email protected]"]
There is no binding for exactly what you want.
The only thing that comes close is Ctrl+F2 which will select all of them at once.
You can bind it to Ctrl+D doing the following:
File > Preferences > Keyboard Shortcuts
It should look something like this:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+d", "command": "editor.action.changeAll",
"when": "editorTextFocus" }
]
You can use values_list alongside filter like so;
active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)
More details here
if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
It help to reduce lot of codes. It is occasionally used in RGB values which consist of 8bits.
where 0xff means 24(0's ) and 8(1's) like 00000000 00000000 00000000 11111111
It effectively masks the variable so it leaves only the value in the last 8 bits, and ignores all the rest of the bits
It’s seen most in cases like when trying to transform color values from a special format to standard RGB values (which is 8 bits long).
You could also use
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')
It's the extended slice notation:
sequence[start:end:step]
In this case, step -1 means backwards, and omitting the start and end means you want the whole string.
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
add
SHELL := /bin/bash
at the top of your makefile I have found it on another question How can I use Bash syntax in Makefile targets?
The locale-independent solution that works on Windows 8.1 is:
chgrp 545 ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
GID 545 is a special ID that always refers to the 'Users' group, even if you locale uses a different word for Users.
@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:
DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]
OUTPUT:
(2 row(s) affected)
Rows ROWCOUNT
----------- -----------
2 1
(1 row(s) affected)
you get Rows
value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT
command affected 1 row
if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:
--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal int
DECLARE @PeachTotal int
SELECT @AppleTotal=0,@PeachTotal=0
BEGIN TRANSACTION
INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
COMMIT
SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal
you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.
Try below code,
$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
$fh = fopen($cookieFile, "w");
fwrite($fh, "");
fclose($fh);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
$response = curl_exec($ch);
}
curl_close($ch);
$result = json_decode($response, true);
echo '<pre>';
var_dump($result);
echo'</pre>';
I hope this will help you.
Best regards, Dasitha.
const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)
try {
async function emitData(directory) {
let filenames = await pathnames
var ob = {}
const data = filenames.map(async function(filename, i) {
if (filename.includes(".")) {
var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
encoding: "utf8",
})
ob[filename.replace(".js", "")] = await storedFile
socket.emit("init", { data: ob })
}
return ob
})
}
emitData(directory)
} catch (err) {
console.log(err)
}
Who wants to try with generators?
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
what I tried:
What Worked:
1. Invalidate caches and restart.
The usual command line ping
tool uses ICMP Echo, but it's true that other protocols can also be used, and they're useful in debugging different kinds of network problems.
I can remember at least arping
(for testing ARP requests) and tcping
(which tries to establish a TCP connection and immediately closes it, it can be used to check if traffic reaches a certain port on a host) off the top of my head, but I'm sure there are others aswell.
if you are using SQL Server use convert
e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate
more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx
You can get a list of all matching elements with a list comprehension:
[x for x in myList if x.n == 30] # list of all elements with .n==30
If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do
def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
To import from an SQL file use the following:
sqlite> .read <filename>
To import from a CSV file you will need to specify the file type and destination table:
sqlite> .mode csv <table>
sqlite> .import <filename> <table>
You can use Integer.parseInt()
or Integer.valueOf()
to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException
it can throw.
It may be helpful to note that valueOf() will return an Integer object, not the primitive int.
@Controller
is used to mark classes as Spring MVC Controller.@RestController
is a convenience annotation that does nothing more than adding the @Controller
and @ResponseBody
annotations (see: Javadoc)So the following two controller definitions should do the same
@Controller
@ResponseBody
public class MyController { }
@RestController
public class MyRestController { }
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
If you're trying to get C's behavior (0 == false
and everything else is true
), you could do this:
boolean uses_votes = Integer.parseInt(o.get("uses_votes")) != 0;
The fundamental way to think about this subject is as follows:
A URI is a resource identifier that uniquely identifies a specific instance of a resource TYPE. Like everything else in life, every object (which is an instance of some type), have set of attributes that are either time-invariant or temporal.
In the example above, a car is a very tangible object that has attributes like make, model and VIN - that never changes, and color, suspension etc. that may change over time. So if we encode the URI with attributes that may change over time (temporal), we may end up with multiple URIs for the same object:
GET /cars/honda/civic/coupe/{vin}/{color=red}
And years later, if the color of this very same car is changed to black:
GET /cars/honda/civic/coupe/{vin}/{color=black}
Note that the car instance itself (the object) has not changed - it's just the color that changed. Having multiple URIs pointing to the same object instance will force you to create multiple URI handlers - this is not an efficient design, and is of course not intuitive.
Therefore, the URI should only consist of parts that will never change and will continue to uniquely identify that resource throughout its lifetime. Everything that may change should be reserved for query parameters, as such:
GET /cars/honda/civic/coupe/{vin}?color={black}
Bottom line - think polymorphism.
You need to make sure, when you run command (install npm -g gulp), it will create install gulp on C:\ directory.
that directory should match with whatver npm path variable set in your java path.
just run path from command prompt, and verify this. if not, change your java class path variable wherever you gulp is instaled.
It should work.
Let me provide complete code for execution protected methods via reflection. It supports any types of params including generics, autoboxed params and null values
@SuppressWarnings("unchecked")
public static <T> T executeSuperMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass().getSuperclass(), instance, methodName, params);
}
public static <T> T executeMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass(), instance, methodName, params);
}
@SuppressWarnings("unchecked")
public static <T> T executeMethod(Class clazz, Object instance, String methodName, Object... params) throws Exception {
Method[] allMethods = clazz.getDeclaredMethods();
if (allMethods != null && allMethods.length > 0) {
Class[] paramClasses = Arrays.stream(params).map(p -> p != null ? p.getClass() : null).toArray(Class[]::new);
for (Method method : allMethods) {
String currentMethodName = method.getName();
if (!currentMethodName.equals(methodName)) {
continue;
}
Type[] pTypes = method.getParameterTypes();
if (pTypes.length == paramClasses.length) {
boolean goodMethod = true;
int i = 0;
for (Type pType : pTypes) {
if (!ClassUtils.isAssignable(paramClasses[i++], (Class<?>) pType)) {
goodMethod = false;
break;
}
}
if (goodMethod) {
method.setAccessible(true);
return (T) method.invoke(instance, params);
}
}
}
throw new MethodNotFoundException("There are no methods found with name " + methodName + " and params " +
Arrays.toString(paramClasses));
}
throw new MethodNotFoundException("There are no methods found with name " + methodName);
}
Method uses apache ClassUtils for checking compatibility of autoboxed params
If you want to extract substrings from a String, not just the position, (but the actual String including emojis). Then, the following maybe a simpler solution.
extension String {
func regex (pattern: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0))
let nsstr = self as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches : [String] = [String]()
regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
(result : NSTextCheckingResult?, _, _) in
if let r = result {
let result = nsstr.substringWithRange(r.range) as String
matches.append(result)
}
}
return matches
} catch {
return [String]()
}
}
}
Example Usage:
"someText ?? pig".regex("??")
Will return the following:
["??"]
Note using "\w+" may produce an unexpected ""
"someText ?? pig".regex("\\w+")
Will return this String array
["someText", "?", "pig"]
For each error of the form:
npm WARN {something} requires a peer of {other thing} but none is installed. You must install peer dependencies yourself.
You should:
$ npm install --save-dev "{other thing}"
Note: The quotes are needed if the {other thing}
has spaces, like in this example:
npm WARN [email protected] requires a peer of rollup@>=0.66.0 <2 but none was installed.
Resolved with:
$ npm install --save-dev "rollup@>=0.66.0 <2"
when you see
Do you want to install from sources the package which needs compilation? (Yes/no/cancel)
answer no
for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this
allEdges <- data.frame(c(edges$V1,edges$V2))
Lucky discovery
if objFolderItem
is Nothing when you call
objFolder.GetDetailsOf(objFolderItem, i)
the string returned is the name of the property, rather than its (undefined) value
e.g. when i=3
it returns "Date modified"
Doing it for all 288 values of I makes it clear why most cause it to return blank for most filetypes
e.g i=175
is "Horizontal resolution"
This
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"¶m2="+lon);
must work. For whatever strange reason1, you need ?
before the first parameter and &
before the following ones.
Using a compound parameter like
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);
would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20
or +
(but this is even worse style).
1 Stating that ?
separates the path and the parameters and that &
separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width
CSS property.
You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:
<div id="container" style="float: left">
<div id="spacer" style="height: 1px; width: 300px"></div>
<button>Button 1 text</button>
<button>Button 2 text</button>
</div>
You should use:
protected void btn1_Click(object sender, EventArgs e)
{
Response.Redirect("otherpage.aspx");
}
What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:
window.onload = function(){
this.keywordsInput.nativeElement.focus();
}
In Visual Studio 2015 Community edition, I've experienced a very (very) slow IDE after changing the "Environment Font" on menu Tools → Options... → Fonts and Colors.
Reverting this options back to the default value ("automatic") solved it immediately.
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
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 was running Eclipse Neon.2 and the Android SDK Build-tools + platform-tools version 26 on Mac OS 10.12.4 and none of the above answers (including the accepted answer) worked for me.
What did work was to
Quit Eclipse
Remove the folder <android-sdk>/build-tools/26.0.0
and to install the (older) version 25.0.3 of the build tools through the Android SDK manager.
Start Eclipse again
You can load an XML document into an XMLType, then query it, e.g.:
DECLARE
x XMLType := XMLType(
'<?xml version="1.0" ?>
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>');
BEGIN
FOR r IN (
SELECT ExtractValue(Value(p),'/row/name/text()') as name
,ExtractValue(Value(p),'/row/Address/State/text()') as state
,ExtractValue(Value(p),'/row/Address/City/text()') as city
FROM TABLE(XMLSequence(Extract(x,'/person/row'))) p
) LOOP
-- do whatever you want with r.name, r.state, r.city
END LOOP;
END;
Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?
To unzip file you can use this script :
zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no
Run docker login
Push the image to docker hub
Re-create pod
This solved the problem for me. Hope it helps.
To add to the above points. Using ArrayList
in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T>
will use much low memory than the ArrayList
.
for example if we use a ArrayList
of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int>
of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.
Source: ArrayList’s vs. generic List for primitive types and 64-bits
All the responses here have been way too complex. You know that the first of the current month is the current date but with 01 as the date. You can just use YEAR() and MONTH() to build the month date by inputting the NOW() method. Here's the solution:
select * from table_name
where date between CONCAT_WS('-', YEAR( NOW() ), MONTH( NOW() ), '01') and DATE( NOW() )
CONCAT_WS() joins a series of strings with a separator (a dash in this case). So if today is 2020-08-28, YEAR( NOW() ) = '2020' and MONTH( NOW() ) = '08' and then you just need to append '01' at the end.
Voila!
instead of this:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
The other solutions might be more best practice, but thought it would be worth sharing.
Well, to calculate the average of an array, you can consider using for
loop instead of while loop.
So as per your question let me assume an array as arrNumbers
( here i'm considering the same array elements as in your question )
int arrNumbers[] = new int[]{1, 3, 2, 5, 8};
int sum = 0;
for(int a = 0; a < arrNumbers.length; a++)
{
sum = sum + arrNumbers[a];
}
double average = sum / arrNumbers.length;
System.out.println("Average is: " + average);
You can use scanner
class as well. It's left to you.
Another easy way is to use:
mysqladmin debug
This dumps a lot of information (including locks) to the error log.
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00
First I think you need to fix your lists, as the first node of a <ul>
must be a <li>
(stackoverflow ref). Once that is setup you can do this:
// note this array has outer scope
var phrases = [];
$('.phrase').each(function(){
// this is inner scope, in reference to the .phrase element
var phrase = '';
$(this).find('li').each(function(){
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if(current.children().size() > 0) {return true;}
// add current text to our current phrase
phrase += current.text();
});
// now that our current phrase is completely build we add it to our outer array
phrases.push(phrase);
});
// note the comma in the alert shows separate phrases
alert(phrases);
Working jsfiddle.
One thing is if you get the .text()
of an upper level li
you will get all sub level text with it.
Keeping an array will allow for many multiple phrases to be extracted.
EDIT:
This should work better with an empty UL
with no LI
:
// outer scope
var phrases = [];
$('.phrase').each(function(){
// inner scope
var phrase = '';
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
// check for sub levels
if(current.children().size() > 0) {
// check is sublevel is just empty UL
var emptyULtest = current.children().eq(0);
if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
phrase += ' -BLANK- '; //custom blank text
return true;
} else {
// else it is an actual sublevel with li's
return true;
}
}
// if it gets to here it is actual li
phrase += current.text();
});
phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
Create Spliterator
from Iterator
using Spliterators
class contains more than one function for creating spliterator, for example here am using spliteratorUnknownSize
which is getting iterator as parameter, then create Stream using StreamSupport
Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize(
iterator, Spliterator.NONNULL);
Stream<Model> stream = StreamSupport.stream(spliterator, false);
If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:
Use a regular expressions to remove carriage returns (\\r
) and line feeds (\\n
) from the beginning (^
) and ending ($
) of a string:
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")
Complete Example:
public class RemoveLineBreaks {
public static void main(String[] args) {
var s = "\nHello\nWorld\n";
System.out.println("before: >"+s+"<");
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
System.out.println("after: >"+s+"<");
}
}
It outputs:
before: >
Hello
World
<
after: >Hello
World<
In Virtual Box "Settings" > System Settings > Processor > Enable the PAE/NX option. It resolved my issue.
For everyone still searching for a solution, I solved it by
bson = require('../../../browser_build/bson.js');
instead of
bson = require(../browser_build/bson.js');
so look if the path is correct.
Steps to find the UDID from IPhone and IPad Without Using itunes
Open below link in your iPhone or iPad : - http://get.udid.io/
Click on the Button Green color - Tap to find UDID
Get your UDID will Appear, Click on the right side top INSTALL button
4 . UDID will appear Copy the UDID.
Yes, that is one way to get the first line of output from a command.
If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:
utility 2>&1 | head -n 1
There are many other ways to capture the first line too, including sed 1q
(quit after first line), sed -n 1p
(only print first line, but read everything), awk 'FNR == 1'
(only print first line, but again, read everything) etc.
For Windows 7,
Control Panel --> Programs --> Uninstall
, then
choose the python package to remove.
Please try below Code that may help you.
@Html.ActionLink(" SignIn", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" ,**@class="glyphicon glyphicon-log-in"** })
Like CodeHater said you are accessing the variable before it is set.
To fix this move the ng-init directive to the first div.
<body ng-app>
<div ng-controller="testController" ng-init="testInput='value'">
<input type="hidden" id="testInput" ng-model="testInput" />
{{ testInput }}
</div>
</body>
That should work!
Maybe someone else need to change color in the XML without create multiple drawables like I needed. Then make a circle drawable without color and then specify backgroundTint for the ImageView.
circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
</shape>
And in your layout:
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/circle"
android:backgroundTint="@color/red"/>
Edit:
There is a bug regarding this method that prevents it from working on Android Lollipop 5.0 (API level 21). But have been fixed in newer versions.
For me the easiest way is to do:
import 'dart:math';
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//where min and max should be specified.
Thanks to @adam-singer explanation in here.
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
be aware that this is dangerous:
WHERE `column` LIKE '%{$needle}%'
do first:
$needle = mysql_real_escape_string($needle);
so it will prevent possible attacks.
I tried all previously mentioned answers, but in my case I had to manually specify the include path of the iostream file. As I use MinGW the path was:
C:\MinGW\lib\gcc\mingw32\4.8.1\include\c++
You can add the path in Eclipse under: Project > C/C++ General > Paths and Symbols > Includes > Add. I hope that helps
I have updated the controller to:
.controller('BusinessCtrl',
function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
$scope.$watch('createBusinessForm.$valid', function(newVal) {
//$scope.valid = newVal;
$scope.informationStatus = true;
});
...
It means that the value type in question is a nullable type
Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a
Nullable<Int32>
, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. ANullable<bool>
can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.class NullableExample { static void Main() { int? num = null; // Is the HasValue property true? if (num.HasValue) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); } // y is set to zero int y = num.GetValueOrDefault(); // num.Value throws an InvalidOperationException if num.HasValue is false try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } } }
It will be increasing because you have a need for temporary storage space, possibly due to a cartesian product or a large sort operation.
The dynamic performance view V$TEMPSEG_USAGE
will help diagnose the cause.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
sys.columns.is_identity = 1
e.g.,
select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
When a folder is created, many Linux filesystems allocate 4096 bytes to store some metadata about the directory itself. This space is increased by a multiple of 4096 bytes as the directory grows.
du command (with or without -b option) take in count this space, as you can see typing:
mkdir test && du -b test
you will have a result of 4096 bytes for an empty dir. So, if you put 2 files of 10000 bytes inside the dir, the total amount given by du -sb would be 24096 bytes.
If you read carefully the question, this is not what asked. The questioner asked:
the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes
that in the example above should be 20000 bytes, not 24096.
So, the correct answer IMHO could be a blend of Nelson answer and hlovdal suggestion to handle filenames containing spaces:
find . -type f -print0 | xargs -0 stat --format=%s | awk '{s+=$1} END {print s}'
Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:
def count_substring(string, sub_string):
cnt = 0
len_ss = len(sub_string)
for i in range(len(string) - len_ss + 1):
if string[i:i+len_ss] == sub_string:
cnt += 1
return cnt
The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.
Disclaimer: I am 'extremly' new to Python programming.
Try this:
list.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Sum of total_vm
is 847170 and sum of rss
is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.
Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.
rss
for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss
and file-rss
.
[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB
Include: #include<stdlib.h>
and use System("cls")
instead of clrscr()
The general issue is just any issue involving Machine/Web/App configs.
I had the same connection strings in Machine.Config as in my App.Config so I put before my first connection string in my App.Config
for me best solotion this is
Thread.CurrentThread.Abort();
and force close app.
So it depends on how you want to pick the incrementer, but this should work:
Range("A1:" & Cells(1, i).Address).Select
Where i
is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)
If you want the beginning to be dynamic as well, you can try this:
Sub SelectCols()
Dim Col1 As Integer
Dim Col2 As Integer
Col1 = 2
Col2 = 4
Range(Cells(1, Col1), Cells(1, Col2)).Select
End Sub
If you install Cygwin. Make sure to select make in the installer. You can then run the following command provided you have a Makefile.
make -f Makefile
https://cygwin.com/install.html
If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.
- (NSArray *)arrayOfStrings {
NSMutableArray *mutableArray = [NSMutableArray array];
mutableArray[0] = @"foo";
mutableArray[1] = @"bar";
return mutableArray;
}
If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy]
.
To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.
The above practice is discussed in more detail here:
Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray
The main difference is that WHERE
cannot be used on grouped item (such as SUM(number)
) whereas HAVING
can.
The reason is the WHERE
is done before the grouping and HAVING
is done after the grouping is done.
I solved this issue to update .htaccess
file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess
in my case).
Just update or add this
php_value max_execution_time 300
line before# END WordPress
. Then save the file and try to install again.
If the error occurs again, you can maximize the value from 300
to 600
.
I think an elegant solution is to use the where
method (also see the API docs
):
In [37]: values = df.Prices * df.Amount
In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)
In [39]: df
Out[39]:
Prices Amount Action Values
0 3 57 Sell 171
1 89 42 Sell 3738
2 45 70 Buy -3150
3 6 43 Sell 258
4 60 47 Sell 2820
5 19 16 Buy -304
6 56 89 Sell 4984
7 3 28 Buy -84
8 56 69 Sell 3864
9 90 49 Buy -4410
Further more this should be the fastest solution.
I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.
try
{
using (var con = new SqlConnection(@"Data Source=..."))
{
var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";
using (var insertCommand = new SqlCommand(cad, con))
{
insertCommand.Parameters.AddWithValue("@r1", atxt);
insertCommand.Parameters.AddWithValue("@r2", btxt);
insertCommand.Parameters.AddWithValue("@r3", ctxt);
con.Open();
insertCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
No matter where's the try/catch placed, the exception will be caught without issues.
This should help, uses simple hash table.
$a1=@(1,2,3,4,5) $b1=@(1,2,3,4,5,6)
$hash= @{}
#storing elements of $a1 in hash
foreach ($i in $a1)
{$hash.Add($i, "present")}
#define blank array $c
$c = @()
#adding uncommon ones in second array to $c and removing common ones from hash
foreach($j in $b1)
{
if(!$hash.ContainsKey($j)){$c = $c+$j}
else {hash.Remove($j)}
}
#now hash is left with uncommon ones in first array, so add them to $c
foreach($k in $hash.keys)
{
$c = $c + $k
}
Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/
1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.
OR:
2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.
This issue often happens when we try to merge another branch changes from a wrong directory.
Ex:
Branch2\Branch1_SubDir$ svn merge -rStart:End Branch1
^^^^^^^^^^^^
Merging at wrong location
A conflict that gets thrown on its execution is :
Tree conflict on 'Branch1_SubDir'
> local missing or deleted or moved away, incoming dir edit upon merge
And when you select q to quit resolution, you get status as:
M .
! C Branch1_SubDir
> local missing or deleted or moved away, incoming dir edit upon merge
! C Branch1_AnotherSubDir
> local missing or deleted or moved away, incoming dir edit upon merge
which clearly means that the merge contains changes related to Branch1_SubDir
and Branch1_AnotherSubDir
, and these folders couldn't be found inside Branch1_SubDir
(obviously a directory can't be inside itself).
How to avoid this issue at first place:
Branch2$ svn merge -rStart:End Branch1
^^^^
Merging at root location
The simplest fix for this issue that worked for me :
svn revert -R .
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
select new { SomeClass = sc, SomeOtherClass = soc };
Would be equivalent to:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new
{
SomeClass = sc,
SomeOtherClass = soc
});
As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.
I was facing this issue running the emulator inside Oracle VirtualBox. For me the solution was to modify the emulator to use an ARM CPU instead of x86.
This seems a lot cleaner than the answer above...
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>
<button onclick="addRow();">Go</button>
You can simply use the border class from bootstrap:
<div class="row border border-dark">
...
</div>
For more details visit the following link: Borders