another.obj = [obj copyWithZone: zone];
I think, that this line causes memory leak, because you access to obj
through property which is (I assume) declared as retain
. So, retain count will be increased by property and copyWithZone
.
I believe it should be:
another.obj = [[obj copyWithZone: zone] autorelease];
or:
SomeOtherObject *temp = [obj copyWithZone: zone];
another.obj = temp;
[temp release];
To do POST you'll need to have a form.
<form action="employee.action" method="post">
<input type="submit" value="Employee1" />
</form>
There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">
By adding a custom view with the background color of your own you can have a custom selection style in table view.
let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView
Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
GitHub Flavored Markdown doesn't support footnotes, but you can manually fake it¹ with Unicode characters or superscript tags, e.g. <sup>1</sup>
.
¹Of course this isn't ideal, as you are now responsible for maintaining the numbering of your footnotes. It works reasonably well if you only have one or two, though.
Try this,
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
System.out.println("Yes option");
} else {
System.out.println("No Option");
}
I generally try to keep all of my packages in one library, but if you want to add a library why not append the new library (which must already exist in your filesystem) to the existing library path?
.libPaths( c( .libPaths(), "~/userLibrary") )
# obviously this would need to be a valid file directory in your OS
# min just happened to be on a Mac that day
Or (and this will make the userLibrary the first place to put new packages):
.libPaths( c( "~/userLibrary" , .libPaths() ) )
Then I get (at least back when I wrote this originally):
> .libPaths()
[1] "/Library/Frameworks/R.framework/Versions/2.15/Resources/library"
[2] "/Users/user_name/userLibrary"
The .libPaths
function is a bit different than most other nongraphics functions. It works via side-effect. The functions Sys.getenv
and Sys.setenv
that report and alter the R environment variables have been split apart but .libPaths
can either report or alter its target.
The information about the R startup process can be read at ?Startup
help page and there is RStudio material at: https://support.rstudio.com/hc/en-us/articles/200549016-Customizing-RStudio
In your case it appears that RStudio is not respecting the Rprofile.site settings or perhaps is overriding them by reading an .Rprofile setting from one of the RStudio defaults. It should also be mentioned that the result from this operation also appends the contents of calls to .Library
and .Library.site
, which is further reason why an RStudio- (or any other IDE or network installed-) hosted R might exhibit different behavior.
Since Sys.getenv()
returns the current system environment for the R process, you can see the library and other paths with:
Sys.getenv()[ grep("LIB|PATH", names(Sys.getenv())) ]
The two that matter for storing and accessing packages are (now different on a Linux box):
R_LIBS_SITE /usr/local/lib/R/site-library:/usr/lib/R/site-library:/usr/lib/R/library
R_LIBS_USER /home/david/R/x86_64-pc-linux-gnu-library/3.5.1/
I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.
1- innerHTML
document.getElementById("ShowButton").innerHTML = 'Show Filter';
You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.
2- innerText
document.getElementById("ShowButton").innerText = 'Show Filter';
This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here
3- textContent
document.getElementById("ShowButton").textContent = 'Show Filter';
This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.
So if a text has to be added like above, then its better to use textContent.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
The only solution that worked for me and $.each
was definitely causing the error. so i used for loop
and it's not throwing error anymore.
Example code
$.ajax({
type: 'GET',
url: 'https://example.com/api',
data: { get_param: 'value' },
success: function (data) {
for (var i = 0; i < data.length; ++i) {
console.log(data[i].NameGerman);
}
}
});
After applying the steps mentioned by ajtrichards you can check if your amazon free tier instance is using swap using this command
cat /proc/meminfo
result:
ubuntu@ip-172-31-24-245:/$ cat /proc/meminfo
MemTotal: 604340 kB
MemFree: 8524 kB
Buffers: 3380 kB
Cached: 398316 kB
SwapCached: 0 kB
Active: 165476 kB
Inactive: 384556 kB
Active(anon): 141344 kB
Inactive(anon): 7248 kB
Active(file): 24132 kB
Inactive(file): 377308 kB
Unevictable: 0 kB
Mlocked: 0 kB
SwapTotal: 1048572 kB
SwapFree: 1048572 kB
Dirty: 0 kB
Writeback: 0 kB
AnonPages: 148368 kB
Mapped: 14304 kB
Shmem: 256 kB
Slab: 26392 kB
SReclaimable: 18648 kB
SUnreclaim: 7744 kB
KernelStack: 736 kB
PageTables: 5060 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 1350740 kB
Committed_AS: 623908 kB
VmallocTotal: 34359738367 kB
VmallocUsed: 7420 kB
VmallocChunk: 34359728748 kB
HardwareCorrupted: 0 kB
AnonHugePages: 0 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
DirectMap4k: 637952 kB
DirectMap2M: 0 kB
An es6 version of Daniel Williams' answer:
function get_table(data) {
let result = ['<table border=1>'];
for(let row of data) {
result.push('<tr>');
for(let cell of row){
result.push(`<td>${cell}</td>`);
}
result.push('</tr>');
}
result.push('</table>');
return result.join('\n');
}
Whenever you update your Gradle files do not forget to check the compatible Gradle wrapper distibutionUrl
, in your case it happened because of the same.
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip
Thank you all for your help, I added this code and it seems it fixed the issue:
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar .navbar-collapse {
text-align: center;
}
Source
The best way using a button is
<input type= 'button' onclick='javascript:history.back();return false;' value='Back'>
Give the table a class name and then you target the td's with the following:
table.classname td {
font-size: 90%;
}
Just after running mysql query from php
get it by
$lastid=mysql_insert_id();
this give you the alst auto increment id value
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
The git diffs have an extra path segment prepended to the file paths. You can strip the this entry in the path by specifying -p1 with patch, like so:
patch -p1 < save.patch
Less than or equal:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than. You can find them all in the documentation.
Update: Apparently possible by passing a flag to mysql_connect()
. See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_
-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
package com.app.download_video_demo;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
// get Picasso jar file and put that jar file in libs folder
public class Youtube_Video_thumnail extends Activity
{
ImageView iv_youtube_thumnail,iv_play;
String videoId;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.youtube_video_activity);
init();
try
{
videoId=extractYoutubeId("http://www.youtube.com/watch?v=t7UxjpUaL3Y");
Log.e("VideoId is->","" + videoId);
String img_url="http://img.youtube.com/vi/"+videoId+"/0.jpg"; // this is link which will give u thumnail image of that video
// picasso jar file download image for u and set image in imagview
Picasso.with(Youtube_Video_thumnail.this)
.load(img_url)
.placeholder(R.drawable.ic_launcher)
.into(iv_youtube_thumnail);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
public void init()
{
iv_youtube_thumnail=(ImageView)findViewById(R.id.img_thumnail);
iv_play=(ImageView)findViewById(R.id.iv_play_pause);
}
// extract youtube video id and return that id
// ex--> "http://www.youtube.com/watch?v=t7UxjpUaL3Y"
// videoid is-->t7UxjpUaL3Y
public String extractYoutubeId(String url) throws MalformedURLException {
String query = new URL(url).getQuery();
String[] param = query.split("&");
String id = null;
for (String row : param) {
String[] param1 = row.split("=");
if (param1[0].equals("v")) {
id = param1[1];
}
}
return id;
}
}
In addition to a performance considerations, there's a functional difference too. When you join comments, you are asking for posts that have comments- an inner join by default. When you include comments, you are asking for all posts- an outer join.
Below is the script which is integrated into ansible and generating dashboard in CSV format.
sh collection.sh
#!/bin/bash
HOSTNAME=`hostname -s`
for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt
sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt
paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt
My output stored in below text files.
cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt
Node.js v10.0.0+
const fs = require('fs')
const { promisify } = require('util')
const pipeline = promisify(require('stream').pipeline)
await pipeline(
fs.createReadStream('source/file/path'),
fs.createWriteStream('destination/file/path')
).catch(err => {
// error handling
})
fs.unlink('source/file/path')
You could use alias python="/usr/bin/python2.7"
:
bash-3.2$ alias
bash-3.2$ python
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
bash-3.2$ alias python="/usr/bin/python3.3"
bash-3.2$ python
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
For example, I will create a table called users
as below and give a column named date
a default value NOW()
create table users_parent (
user_id varchar(50),
full_name varchar(240),
login_id_1 varchar(50),
date timestamp NOT NULL DEFAULT NOW()
);
Thanks
had better be
List
The only List
implementation in java.util.concurrent
is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.
That said, are you sure you need it to be a List
? There are a lot more options for concurrent Queue
s and Map
s (and you can make Set
s from Map
s), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.
For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:
In the source root:
git reset ./ HEAD <--un-stage any staged changes
git checkout ./ <--discard any unstaged changes
Other answers have gone over the basics of what each thing is. At the higher level, a flowchart is a design level tool, while DFDs are more analysis.
DFDs have some nice features. Since they show the flow of data, some things become more obvious when charted this way: some data is only used by a few routines, some routines use only some bits of data, some routines touch everything. Seeing that up front helps organize, restructuring, and planning.
A follow-on worth exploring is the Event-Response Diagram, which is basically a DFD only showing process and data needed to process an "event", meaning something triggered externally (customer makes payment, etc.).
More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:
Delete this folder after every few days interval. Most of the time, it occupy huge space!
~/Library/Developer/Xcode/DerivedData
All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.
~/Library/Developer/Xcode/Archives
iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.
~/Library/Developer/Xcode/iOS DeviceSupport
Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.
~/Library/Developer/CoreSimulator
(Here's a handy shell command for step 5: xcrun simctl delete unavailable
)
Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!
~/Library/Caches/com.apple.dt.Xcode
Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.
~/Library/Application Support/MobileSync/Backup
Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac
I got back about 40GB!
Small reusable method can be written for creating person json object to avoid duplicate code
JSONObject getPerson(String firstName, String lastName){
JSONObject person = new JSONObject();
person .put("firstName", firstName);
person .put("lastName", lastName);
return person ;
}
public JSONObject getJsonResponse(){
JSONArray employees = new JSONArray();
employees.put(getPerson("John","Doe"));
employees.put(getPerson("Anna","Smith"));
employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
managers.put(getPerson("John","Doe"));
managers.put(getPerson("Anna","Smith"));
managers.put(getPerson("Peter","Jones"));
JSONObject response= new JSONObject();
response.put("employees", employees );
response.put("manager", managers );
return response;
}
While you are in it, I suggest to remember some key facts about compareTo() methods
CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.
CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.
Read more: http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3
Add empty tr
before your table tr tags.
There is an another option to insert data into table ..
insert into tablename values(&column_name1,&column_name2,&column_name3);
it will open another window for inserting the data value..
When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url)
works fine , most server disable this feature for security reason.
Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:
If you are on windows, the following for loop will revert all uncommitted changes made to your workspace:
for /F "tokens=1,*" %%d in ('svn st') do (
svn revert "%%e"
)
If you want to remove all uncommitted changes and all unversioned objects, it will require 2 loops:
for /F "tokens=1,*" %%d in ('svn st') do (
svn revert "%%e"
)
for /F "tokens=1,*" %%d in ('svn st') do (
svn rm --force "%%e"
)
I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.
Look at BackgroundWorker.ReportProgress()
to see how to report progress back to the UI thread.
For example:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
progressBar1.Value = 0;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
for (int j = 0; j < 100000; j++)
{
Calculate(j);
backgroundWorker.ReportProgress((j * 100) / 100000);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// TODO: do something with final calculation.
}
An analytic solution with only one nested query:
SELECT * FROM
(
SELECT t.*, Row_Number() OVER (ORDER BY name) MyRow FROM sometable t
)
WHERE MyRow BETWEEN 10 AND 20;
Rank()
could be substituted for Row_Number()
but might return more records than you are expecting if there are duplicate values for name.
I think you just need;
List<string> list = new List<string>();
list.Add("hai");
There is a difference between
List<string> list;
and
List<string> list = new List<string>();
When you didn't use new
keyword in this case, your list
didn't initialized. And when you try to add it hai
, obviously you get an error.
Also see: the official Which remote URL should I use? answer on help.github.com.
EDIT:
It seems that it's no longer necessary to have write access to a public repo to use an SSH URL, rendering my original explanation invalid.
ORIGINAL:
Apparently the main reason for favoring HTTPS URLs is that SSH URL's won't work with a public repo if you don't have write access to that repo.
The use of SSH URLs is encouraged for deployment to production servers, however - presumably the context here is services like Heroku.
You could start the container setting a container name:
docker run -d --name <container-name> <image-name>
The same image could be used to spin up multiple containers, so this is a good way to start a container. Then you could use this container-name to stop, attach... the container:
docker exec -it <container-name> bash
docker stop <container-name>
docker rm <container-name>
You can rather pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana') OR
var someValue = 'Dolce & Gabbana';
data : "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.
Then you can use either _.size(object)
or _.keys(object).length
For your obj.Data
, you could test this with:
console.log( _.size(obj.Data) );
or:
console.log( _.keys(obj.Data).length );
Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)
Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:
function ObjectLength( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
You can test this with:
console.log( ObjectLength(obj.Data) );
That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:
function ObjectLength_Modern( object ) {
return Object.keys(object).length;
}
function ObjectLength_Legacy( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
}
var ObjectLength =
Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;
and as before, test it with:
console.log( ObjectLength(obj.Data) );
This code uses Object.keys(object).length
in modern browsers and falls back to counting in a loop for old browsers.
But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.
I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.
Thanks to Barmar for suggesting Object.keys
for newer browsers in his answer.
use below line of code in the case of spring boot applications.
@EntityScan(basePackageClasses=YourClassName.class)
You have to add just the NSAllowsArbitraryLoads key to YES in NSAppTransportSecurity dictionary in your info.plist file.
For example,
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
It seems as though the "sr-only" element and its styles inside of the table are what's causing this bug. At least I had the same issue and after months of banging our head against the wall that's what we determined the cause was, though I still don't understand why. Adding left:0
to the "sr-only" styles fixed it.
.subscribe
is not an Angular2 thing.
It's a method that comes from rxjs
library which Angular is using internally.
If you can imagine yourself subscribing to a newsletter, every time there is a new newsletter, they will send it to your home (the method inside subscribe gets called).
That's what happens when you subscribing to a source of magazines ( which is called an Observable
in rxjs
library)
All the AJAX
calls in Angular are using rxjs
internally and in order to use any of them, you've got to use the method name, e.g get
, and then call subscribe on it, because get
returns and Observable
.
Also, when writing this code <button (click)="doSomething()">
, Angular is using Observables
internally and subscribes you to that source of event, which in this case is a click
event.
Back to our analogy of Observables
and newsletter stores
, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe
from them for which you have to remember the subscription number or id, which in rxjs
case it would be like :
let subscription = magazineStore.getMagazines().subscribe(
(newMagazine)=>{
console.log('newMagazine',newMagazine);
});
And when you don't want to get the magazines anymore:
subscription.unsubscribe();
Also, the same goes for
this.route.paramMap
which is returning an Observable
and then you're subscribing to it.
My personal view is rxjs
was one of the greatest things that were brought to JavaScript world and it's even better in Angular.
There are 150~ rxjs
methods ( very similar to lodash
methods) and the one that you're using is called switchMap
EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.
Here is an example of how it could work:
HTML:
<div id="someDiv">
Once upon a midnight dreary
<br>While I pondered weak and weary
<br>Over many a quaint and curious
<br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />
<input type="hidden" id="vault" />
javascript/jQuery:
//Declare persistent vars outside function
var savText, newText, myState = 0;
$('#mybutt').click(function(){
if (myState==0){
savText = $('#someDiv').html(); //save poem data from DIV
newText = $('#replacementtext').val(); //save data from input field
$('#replacementtext').val(''); //clear input field
$('#someDiv').html( newText ); //replace poem with insert field data
myState = 1; //remember swap has been done once
} else {
$('#someDiv').html(savText);
$('#replacementtext').val(newText); //replace contents
myState = 0;
}
});
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
When building on the build/CI server, turn off the import of Microsoft.WebApplication.targets
altogether by specifying /p:VSToolsPath=''
. This will, essentially, make the condition of the following line false:
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
This is how it's done in TeamCity:
since iOS4 it can be obviously done with blocks:
[UIView animateWithDuration:1.0
animations:^{
label.alpha = 0.0f;
label.text = newText;
label.alpha = 1.0f;
}];
I faced the same issue today,
And solved it easily by following points
1) Start the StandAlone SDK manager (To open the standalone sdk manager - Tools>Android>SDKManager> at Bottom YOu will see a link to launch StandAlone SDK manager)
2) Delete tha package of SDK Build Tools that you have already installed for e.g 24.0.0 rc4.
3) Close the standalone SDK manager then Restart Android Studio.
4) Once after restart the gradle will start building the project and you will get an alert download the package of SDK build tool and Sync. CLick on that and you will start downloading like that...
I hope this helps
Please try this for get the url of root file.
First Way:
$path = get_home_path();
print "Path: ".$path;
// Return "Path: /var/www/htdocs/" or
// "Path: /var/www/htdocs/wordpress/" if it is subfolder
Second Way:
And you can also use
"ABSPATH"
this constant is define in wordpress config file.
If you want to do the redirection within the Python script, setting sys.stdout
to a file object does the trick:
import sys
sys.stdout = open('file', 'w')
print('test')
sys.stdout.close()
A far more common method is to use shell redirection when executing (same on Windows and Linux):
$ python foo.py > file
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
You can make the column hidden
on the server side and for some reason this is different to doing it the aspx
code. It can still be referenced as if it was visible. Just add this code to your OnDataBound
event.
protected void gvSearchResults_DataBound(object sender, EventArgs e)
{
GridView gridView = (GridView)sender;
if (gridView.HeaderRow != null && gridView.HeaderRow.Cells.Count > 0)
{
gridView.HeaderRow.Cells[UserIdColumnIndex].Visible = false;
}
foreach (GridViewRow row in gvSearchResults.Rows)
{
row.Cells[UserIdColumnIndex].Visible = false;
}
}
I know the purists will hate this method, but you can cat
the file.
NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
echo "$NAME"
done
For Linux you click on the three dots "..." beside the emulator, on Virtual sensors check "Move" and then try quickly moving either x, y or z coordinates.
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
Here is another nice solution for the Max
functionality using T-SQL and SQL Server
SELECT [Other Fields],
(SELECT Max(v)
FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]
FROM [YourTableName]
Additionally, if you want to center both horizontally and vertically -instead of having a flow-design (in such cases, the previous solutions apply)- you could do:
absolute
or relative
positioning (I call it content
).wrapper
).wrapper
div.#content {_x000D_
width: 5em;_x000D_
height: 5em;_x000D_
border: 1px solid;_x000D_
border-color: red;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
width: 4em;_x000D_
height: 4em;_x000D_
border: 3px solid;_x000D_
border-color: black;_x000D_
position: absolute;_x000D_
left: 50%; top: 50%; /*move the object to the center of the parent object*/_x000D_
-webkit-transform: translate(-50%, -50%);_x000D_
-moz-transform: translate(-50%, -50%);_x000D_
-ms-transform: translate(-50%, -50%);_x000D_
-o-transform: translate(-50%, -50%);_x000D_
transform: translate(-50%, -50%);_x000D_
/*these 5 settings change the base (or registration) point of the wrapper object to it's own center - so we align child center with parent center*/_x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
border: 1px solid;_x000D_
border-color: yellow;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="content">_x000D_
<div id="wrapper">_x000D_
<table>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
Note: You cannot get rid of the wrapper div, since this style does not work directly on tables, so I use a div to wrap it and position it, while the table is flowed inside the div.
You can alternatively use NamedParameterJdbcTemplate
(naming can be useful when you have many parameters)
Map<String, Object> params = new HashMap<>();
params.put("var1",value1);
params.put("var2",value2);
namedJdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (:var1, :var2)",
params
);
I have used the answer given by senderle for a long time until I discovered np.argsort
.
Here is how it works.
# idx works on np.array and not lists.
list1 = np.array([3,2,4,1])
list2 = np.array(["three","two","four","one"])
idx = np.argsort(list1)
list1 = np.array(list1)[idx]
list2 = np.array(list2)[idx]
I find this solution more intuitive, and it works really well. The perfomance:
def sorting(l1, l2):
# l1 and l2 has to be numpy arrays
idx = np.argsort(l1)
return l1[idx], l2[idx]
# list1 and list2 are np.arrays here...
%timeit sorting(list1, list2)
100000 loops, best of 3: 3.53 us per loop
# This works best when the lists are NOT np.array
%timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 2.41 us per loop
# 0.01us better for np.array (I think this is negligible)
%timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best for 3 loops: 1.96 us per loop
Even though np.argsort
isn't the fastest one, I find it easier to use.
Another way is with Arrays.setAll
, or Arrays.fill
:
String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]
Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]
This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
From my experience, you don't need to do anything particular about file fields, you just tell it to make use of the file field:
from rest_framework import routers, serializers, viewsets
class Photo(django.db.models.Model):
file = django.db.models.ImageField()
def __str__(self):
return self.file.name
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Photo
fields = ('id', 'file') # <-- HERE
class PhotoViewSet(viewsets.ModelViewSet):
queryset = models.Photo.objects.all()
serializer_class = PhotoSerializer
router = routers.DefaultRouter()
router.register(r'photos', PhotoViewSet)
api_urlpatterns = ([
url('', include(router.urls)),
], 'api')
urlpatterns += [
url(r'^api/', include(api_urlpatterns)),
]
and you're ready to upload files:
curl -sS http://example.com/api/photos/ -F 'file=@/path/to/file'
Add -F field=value
for each extra field your model has. And don't forget to add authentication.
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.
I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar
import net.sf.json.JSONObject;
...
public void send()
{
//put attributes
Map m = New HashMap();
m.put("send_to","[email protected]");
m.put("email_subject","this is a test email");
m.put("email_content","test email content");
//generate JSON Object
JSONObject json = JSONObject.fromObject(content);
String message = json.toString();
...
}
public void receive(String jsonMessage)
{
//parse attributes
JSONObject json = JSONObject.fromObject(jsonMessage);
String to = (String) json.get("send_to");
String title = (String) json.get("email_subject");
String content = (String) json.get("email_content");
...
}
More samples here http://json-lib.sourceforge.net/usage.html
You can use .issubset() as well
>>> {"key1", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
True
>>> {"key4", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
False
>>>
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
you may change your loop condition according to following code, when length of l is smaller than buffer size it means that it reached end of file
while (True):
print "Receiving..."
l = c.recv(1024)
f.write(l)
if len(l) < 1024:
break
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
font-size: 14px;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
function initialize() {_x000D_
var input = document.getElementById('searchTextField');_x000D_
var options = {_x000D_
types: ['geocode'] //this should work !_x000D_
};_x000D_
var autocomplete = new google.maps.places.Autocomplete(input, options);_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
var options = {
types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2
Sometimes is worth to remove new line characters \n
like:
conn.exec <<-eos.squish
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos
I'm getting an index out of range error with the accepted answer solution. Reason: When range start, it is not iterate value one by one, it is iterate by index. If you modified a slice while it is in range, it will induce some problem.
Old Answer:
chars := []string{"a", "a", "b"}
for i, v := range chars {
fmt.Printf("%+v, %d, %s\n", chars, i, v)
if v == "a" {
chars = append(chars[:i], chars[i+1:]...)
}
}
fmt.Printf("%+v", chars)
Expected :
[a a b], 0, a
[a b], 0, a
[b], 0, b
Result: [b]
Actual:
// Autual
[a a b], 0, a
[a b], 1, b
[a b], 2, b
Result: [a b]
Correct Way (Solution):
chars := []string{"a", "a", "b"}
for i := 0; i < len(chars); i++ {
if chars[i] == "a" {
chars = append(chars[:i], chars[i+1:]...)
i-- // form the remove item index to start iterate next item
}
}
fmt.Printf("%+v", chars)
Source: https://dinolai.com/notes/golang/golang-delete-slice-item-in-range-problem.html
You can use %
sed -i "s%http://www.fubar.com%URL_FUBAR%g"
GIMP ( Graphic Image Manipulation Program) does a pretty good job... http://www.makeuseof.com/tag/create-image-map-gimp/
If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.
You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.
If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.
The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.
Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.
There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.
There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are
None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals
The benefit of WireShark is that it could possibly show you errors in levels below the HTTP protocol. Fiddler will show you errors in the HTTP protocol.
If you think the problem is somewhere in the HTTP request issued by the browser, or you are just looking for more information in regards to what the server is responding with, or how long it is taking to respond, Fiddler should do.
If you suspect something may be wrong in the TCP/IP protocol used by your browser and the server (or in other layers below that), go with WireShark.
I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.
This is the method for rotating the Matrix:
this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY());
(this.getCenterX()
is basically the bitmaps X position + the bitmaps width / 2)
And the method for Drawing the bitmap (called via a RenderManager
Class):
canvas.drawBitmap(this.bitmap, this.matrix, null);
So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate
followed by postTranslate
. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/
Anyways, thanks for your help!
In your view:
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }}</p>
@endif
@endforeach
</div>
Then set a flash message in the controller:
Session::flash('alert-danger', 'danger');
Session::flash('alert-warning', 'warning');
Session::flash('alert-success', 'success');
Session::flash('alert-info', 'info');
Assuming you're on x86 and game for a bit of inline assembler, Intel provides a BSR
instruction ("bit scan reverse"). It's fast on some x86s (microcoded on others). From the manual:
Searches the source operand for the most significant set bit (1 bit). If a most significant 1 bit is found, its bit index is stored in the destination operand. The source operand can be a register or a memory location; the destination operand is a register. The bit index is an unsigned offset from bit 0 of the source operand. If the content source operand is 0, the content of the destination operand is undefined.
(If you're on PowerPC there's a similar cntlz
("count leading zeros") instruction.)
Example code for gcc:
#include <iostream>
int main (int,char**)
{
int n=1;
for (;;++n) {
int msb;
asm("bsrl %1,%0" : "=r"(msb) : "r"(n));
std::cout << n << " : " << msb << std::endl;
}
return 0;
}
See also this inline assembler tutorial, which shows (section 9.4) it being considerably faster than looping code.
You can do it with ViewModels like how you passed data from your controller to view.
Assume you have a viewmodel like this
public class ReportViewModel
{
public string Name { set;get;}
}
and in your GET Action,
public ActionResult Report()
{
return View(new ReportViewModel());
}
and your view must be strongly typed to ReportViewModel
@model ReportViewModel
@using(Html.BeginForm())
{
Report NAme : @Html.TextBoxFor(s=>s.Name)
<input type="submit" value="Generate report" />
}
and in your HttpPost action method in your controller
[HttpPost]
public ActionResult Report(ReportViewModel model)
{
//check for model.Name property value now
//to do : Return something
}
OR Simply, you can do this without the POCO classes (Viewmodels)
@using(Html.BeginForm())
{
<input type="text" name="reportName" />
<input type="submit" />
}
and in your HttpPost action, use a parameter with same name as the textbox name.
[HttpPost]
public ActionResult Report(string reportName)
{
//check for reportName parameter value now
//to do : Return something
}
EDIT : As per the comment
If you want to post to another controller, you may use this overload of the BeginForm method.
@using(Html.BeginForm("Report","SomeOtherControllerName"))
{
<input type="text" name="reportName" />
<input type="submit" />
}
You can use the same view model, simply set the property values in your GET action method
public ActionResult Report()
{
var vm = new ReportViewModel();
vm.Name="SuperManReport";
return View(vm);
}
and in your view
@model ReportViewModel
<h2>@Model.Name</h2>
<p>Can have input field with value set in action method</p>
@using(Html.BeginForm())
{
@Html.TextBoxFor(s=>s.Name)
<input type="submit" />
}
I use sudo apt remove python3-pip
then pip
works.
~ sudo pip install pip --upgrade
[sudo] password for sen:
Traceback (most recent call last):
File "/usr/bin/pip", line 9, in <module>
from pip import main
ImportError: cannot import name 'main'
? ~ sudo apt remove python3-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libexpat1-dev libpython3-dev libpython3.5-dev python-pip-whl python3-dev python3-wheel
python3.5-dev
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED:
python3-pip
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 569 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 215769 files and directories currently installed.)
Removing python3-pip (8.1.1-2ubuntu0.4) ...
Processing triggers for man-db (2.7.5-1) ...
? ~ pip
Usage:
pip <command> [options]
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
As per the above answers, it works well.
If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.
This is just an example. Your API should be a different one (if your API allows)
curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
-H 'secret: secret' \
-H 'email: [email protected]' \
-H 'accept: application/json, text/plain, */*' \
-H 'authorizationtoken: bearer' \
-F 'referenceFilePath= Add file path' \
--compressed
I'm a begin fan of js array's reduce function.
const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)
In fact if you really want to get fancy you can create a count function on the Array prototype. Then you can reuse it.
Array.prototype.count = function(filterMethod) {
return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
}
Then do
const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)
Use the pickle
module to save it to disk and load later on.
Pretty easy in your controller you do:
public function create()
{
$user = new User;
$action = URL::route('user.store');
return View::('viewname')->with(compact('user', 'action'));
}
public function edit($id)
{
$user = User::find($id);
$action = URL::route('user.update', ['id' => $id]);
return View::('viewname')->with(compact('user', 'action'));
}
And you just have to use this way:
{{ Form::model($user, ['action' => $action]) }}
{{ Form::input('email') }}
{{ Form::input('first_name') }}
{{ Form::close() }}
The slicing problem is serious because it can result in memory corruption, and it is very difficult to guarantee a program does not suffer from it. To design it out of the language, classes that support inheritance should be accessible by reference only (not by value). The D programming language has this property.
Consider class A, and class B derived from A. Memory corruption can happen if the A part has a pointer p, and a B instance that points p to B's additional data. Then, when the additional data gets sliced off, p is pointing to garbage.
I had the same issue on macos with python 2 and 3 installed.
Also, I had aliases to point to python3 and pip3 in my .bash_profile
.
alias python=/usr/local/bin/python3
alias pip=/usr/local/bin/pip3
Removing aliases and recreating virtual env using python3 -m venv venv
fixed the issue.
It should be noted that math.floor()
always rounds down, and therefore does not yield a sensible result for negative floating point values.
For example, -10.4 represented as an integer would usually be either truncated or rounded to -10. Yet the result of math.floor() is not the same:
math.floor(-10.4) => -11
For truncation with type conversion, the following helper function will work:
function tointeger( x )
num = tonumber( x )
return num < 0 and math.ceil( num ) or math.floor( num )
end
Reference: http://lua.2524044.n2.nabble.com/5-3-Converting-a-floating-point-number-to-integer-td7664081.html
You need to tell the browser you are using javascript:
<a href="javascript:history.back(1)">Back</a>
Also, your input element seems out of place in your code.
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
Maybe you should just write the ImageView first and the TextView second. That can help sometimes. That's simple but I hope it helps somebody. :)
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:
Same issue here, comparing the htdocs/xampp folder in 5.6.11 with 5.6.8 I saw all the files there are missing in 5.6.11. Copied the entire htdocs/xampp folder from 5.6.8 to 5.6.11 and worked fine.
If you are using the Android Support Library you can use ConfigurationCompat
instead of @Makalele's method to get rid of deprecation warnings:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
or in Kotlin:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
If you use %pylab inline
you can (on a new line) insert the following command:
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
This will set all figures in your document (unless otherwise specified) to be of the size (10, 6)
, where the first entry is the width and the second is the height.
See this SO post for more details. https://stackoverflow.com/a/17231361/1419668
For scoop users:
"terminal.integrated.shell.windows": "C:\\Users\\[YOUR-NAME]\\scoop\\apps\\git\\current\\usr\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": [
"-l",
"-i"
],
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
And if you want to access more than one column at a time you could do:
>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
[3, 5],
[6, 8]])
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
You can find it like
SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%User%'
It will list distinct stored procedure names that contain text like 'User' inside stored procedure. More info
My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:
CREATE TABLE book (
id INT AUTO_INCREMENT NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL,
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
mbstring is a "non-default" extension, that is not enabled by default ; see this page of the manual :
Installation
mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details
So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account)
I don't use CentOS, but you may have to install the extension first, using something like this (see this page, for instance, which seems to give a solution) :
yum install php-mbstring
(The package name might be a bit different ; so, use yum search to get it :-) )
We use the bulk insert as well. The file we upload is sent from an external party. After a while of troubleshooting, I realized that their file had columns with commas in it. Just another thing to look for...
check with the below code :
XML CODE :
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinatorParent"
style="@style/parentLayoutPaddingStyle"
android:layout_width="match_parent"
android:layout_height="match_parent">
.................
</android.support.constraint.ConstraintLayout>
JAVA CODE :
//Global Variable
android.support.constraint.ConstraintLayout activityRootView;
boolean isKeyboardShowing = false;
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
android.support.constraint.ConstraintLayout.LayoutParams layoutParams;
//onCreate or onViewAttached
activityRootView = view.findViewById(R.id.coordinatorParent);
onGlobalLayoutListener = onGlobalLayoutListener();
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
//outside oncreate
ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener() {
return new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
int screenHeight = activityRootView.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
if (!isKeyboardShowing) { // keyboard is opened
isKeyboardShowing = true;
onKeyboardVisibilityChanged(true);
}
}
else {
if (isKeyboardShowing) { // keyboard is closed
isKeyboardShowing = false;
onKeyboardVisibilityChanged(false);
}
}
}//ends here
};
}
void onKeyboardVisibilityChanged(boolean value) {
layoutParams = (android.support.constraint.ConstraintLayout.LayoutParams)topImg.getLayoutParams();
if(value){
int length = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, getResources().getDisplayMetrics());
layoutParams.height= length;
layoutParams.width = length;
topImg.setLayoutParams(layoutParams);
Log.i("keyboard " ,""+ value);
}else{
int length1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 175, getResources().getDisplayMetrics());
layoutParams.height= length1;
layoutParams.width = length1;
topImg.setLayoutParams(layoutParams);
Log.i("keyboard " ,""+ value);
}
}
@Override
public void onDetach() {
super.onDetach();
if(onGlobalLayoutListener != null) {
activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
}
}
creating local.properties
file in the root directory solved my issue
I somehow lost this file after pulling from GitHub
this is how my local.properties
file looks like now:
## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Sat Feb 06 11:53:03 EST 2016
sdk.dir=/Users/****/Library/Android/sdk
Write a custom method like this:
public Object findByYourField(Class entityClass, String yourFieldValue)
{
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(entityClass);
Root<Object> root = criteriaQuery.from(entityClass);
criteriaQuery.select(root);
ParameterExpression<String> params = criteriaBuilder.parameter(String.class);
criteriaQuery.where(criteriaBuilder.equal(root.get("yourField"), params));
TypedQuery<Object> query = entityManager.createQuery(criteriaQuery);
query.setParameter(params, yourFieldValue);
List<Object> queryResult = query.getResultList();
Object returnObject = null;
if (CollectionUtils.isNotEmpty(queryResult)) {
returnObject = queryResult.get(0);
}
return returnObject;
}
read last 3 characters from string [Initially asked question]
You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.
myString.Substring(myString.Length-3)
Retrieves a substring from this instance. The substring starts at a specified character position. MSDN
Edit, for updated post
Remove last 3 characters from string [Updated question]
To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0
and end index three less than the string length. It will get the substring before last three characters.
myString = myString.Substring(0, myString.Length-3);
String.Substring Method (Int32, Int32)
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.
myString = myString.Remove(myString.Length-3)
Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted
You may run into scenarios where even killing the thread or process won't actually terminate the app (this happens for me on Linux and Windows every once in a while). Sometimes you might already have an instance running that you didn't close.
As a result of those kinds of circumstances, I prefer to add to my package.json
:
"scripts": {
"stop-win": "Taskkill /IM node.exe /F",
"stop-linux": "killall node"
},
I can then call them using:
npm run stop-win
npm run stop-Linux
You can get fancier and make those BIN commands with an argument flag if you want. You can also add those as commands to be executed within a try-catch clause.
Without seeing more of the surrounding code I can't give a definite answer, but I have two theories.
You're not using UIViewController
's designated initializer initWithNibName:bundle:
. Try using it instead of just init
.
Also, self
may be one of the tab bar controller's view controllers. Always present view controllers from the topmost view controller, which means in this case ask the tab bar controller to present the overlay view controller on behalf of the view controller. You can still keep any callback delegates to the real view controller, but you must have the tab bar controller present and dismiss.
When you create a virtual device from Android Studio pay attention to the Play Store Column in the device table. The images with the play store icon have google play pre-installed.
?? In system images that come with google play root is not available.
After you've created the AVD you'll also be able to see from the Android Studio AVD Manager which of your images have google play installed:
Simple!
System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
On OS X Sierra 10.12, None of the above work.
cd then drag and drop does not work.
No spacing or other fixes work.
I cannot cd into ~/Library Support using any technique that I can find.
Is this a security feature?
I'm going to try disabling SIP and see if it makes a difference.
You can simply place multiple name together separated by a white space like
C:\Users\Dell>pip install markdown django-filter
#c:\Users\Dell is path in my pc this can be anything on yours
this installed markdown and django-filter on my device.
Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"
sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy
The filter option filters only the first level subkey below ansible_facts
package-lock.json
: It contains the exact version details that is currently installed for your Application.
+
means "one or more characters" and without the plus it means "one character." In your case both result in the same output.
I mostly use lstlistings in papers, but for coloured output (for slides) I use pygments instead.
One needs to install magrittr
as follows
install.packages("magrittr")
Then, in one's script, don't forget to add on top
library(magrittr)
For the meaning of the operator %>%
you might want to consider this question: What does %>% function mean in R?
Note that the same operator would also work with the library dplyr
, as it imports from magrittr
.
dplyr
used to have a similar operator (%.%
), which is now deprecated. Here we can read about the differences between %.%
(deprecated operator from the library dplyr
) and %>%
(operator from magrittr
, that is also available in dplyr
)
your compilation option -c makes your compiling just compilation and assembly, but no link.
Yes, they're both JavaScript, you can use whichever functions are appropriate for the situation.
In this case you can just put the code in a document.ready
handler, like this:
$(function() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
});
Agree with @Pom12, @abayer. To complete the answer you need to add script block
Try something like this:
pipeline {
agent any
environment {
ENV_NAME = "${env.BRANCH_NAME}"
}
// ----------------
stages {
stage('Build Container') {
steps {
echo 'Building Container..'
script {
if (ENVIRONMENT_NAME == 'development') {
ENV_NAME = 'Development'
} else if (ENVIRONMENT_NAME == 'release') {
ENV_NAME = 'Production'
}
}
echo 'Building Branch: ' + env.BRANCH_NAME
echo 'Build Number: ' + env.BUILD_NUMBER
echo 'Building Environment: ' + ENV_NAME
echo "Running your service with environemnt ${ENV_NAME} now"
}
}
}
}
Given a String str:
str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")
arrList.set(5,newValue);
and if u want to update it then add this line also
youradapater.NotifyDataSetChanged();
class Test {
public function yo() {
return 'yoes';
}
}
$var = 'Test';
$obj = new $var();
echo $obj->yo(); //yoes
I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:
response.sendRedirect("simpleList.do")
In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.
I got this warning using Pandas 0.22. You can avoid this by being very explicit using the assign method:
df = df.assign(quantity = df.quantity.mul(-1))
you can try this.
switch (Valor) { case (Valor1 & Valor2): break; }
I'd recommend using the Buffer
class:
var someEncodedString = Buffer.from('someString', 'utf-8');
This avoids any unnecessary dependencies that other answers require, since Buffer
is included with node.js
, and is already defined in the global scope.
Here is an Interceptor
that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers):
public class TimberLoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Timber.i("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers());
Timber.v("REQUEST BODY BEGIN\n%s\nREQUEST BODY END", bodyToString(request));
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
String responseBodyString = response.body().string();
// now we have extracted the response body but in the process
// we have consumed the original reponse and can't read it again
// so we need to build a new one to return from this method
Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();
long t2 = System.nanoTime();
Timber.i("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers());
Timber.v("RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyString);
return newResponse;
}
private static String bodyToString(final Request request){
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}
If these are folders you want to ignore in a certain workspace, you can go to:
AppMenu > Preferences > Workspace Settings
Otherwise, if you want these folders to be ignored in all your workspaces, go to:
AppMenu > Preferences > User Settings
and add the following to your configuration:
//-------- Search configuration --------
// The folders to exclude when doing a full text search in the workspace.
"search.excludeFolders": [
".git",
"node_modules",
"bower_components",
"path/to/other/folder/to/exclude"
],
The difference between workspace and user settings is explained in the customization docs
You can use the Interval
class from Eclipse Collections.
List<Integer> range = Interval.oneTo(10);
range.forEach(System.out::print); // prints 12345678910
The Interval
class is lazy, so doesn't store all of the values.
LazyIterable<Integer> range = Interval.oneTo(10);
System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10
Your method would be able to be implemented as follows:
public List<Integer> makeSequence(int begin, int end) {
return Interval.fromTo(begin, end);
}
If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList
with IntInterval
from Eclipse Collections.
public IntList makeSequence(int begin, int end) {
return IntInterval.fromTo(begin, end);
}
IntList
has the methods sum()
, min()
, minIfEmpty()
, max()
, maxIfEmpty()
, average()
and median()
available on the interface.
Update for clarity: 11/27/2017
An Interval
is a List<Integer>
, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List
, Set
or Bag
as follows:
Interval integers = Interval.oneTo(10);
Set<Integer> set = integers.toSet();
List<Integer> list = integers.toList();
Bag<Integer> bag = integers.toBag();
An IntInterval
is an ImmutableIntList
which extends IntList
. It also has converter methods.
IntInterval ints = IntInterval.oneTo(10);
IntSet set = ints.toSet();
IntList list = ints.toList();
IntBag bag = ints.toBag();
An Interval
and an IntInterval
do not have the same equals
contract.
Update for Eclipse Collections 9.0
You can now create primitive collections from primitive streams. There are withAll
and ofAll
methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.
Assert.assertEquals(
IntInterval.oneTo(10),
IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));
Assert.assertEquals(
IntInterval.oneTo(10),
IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));
Note: I am a committer for Eclipse Collections
If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:
$my_array = array_diff($my_array, array('Value_to_remove'));
For example:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
This displays the following:
4
3
In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.
If this is for an intranet application and all of the clients use DHCP, you can query the DHCP server for the MAC address for a given IP address.
Even nicer is this version I created from a plugin I found:
function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
Note from filesize() doc
Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB
I had to use nl2br to display the carriage returns correctly and it worked for me:
<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>
Another basic example:
NOT working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
Working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
So basically: just add .bind(this) to your function
Replace whatever is in the address bar with this:
javascript:document.getElementById('serverTime').innerHTML='[text here]';
You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):
<div id="printOption">
<a href="javascript:void();"
onclick="document.getElementById('printOption').style.visibility = 'hidden';
document.print();
return true;">
Print
</a>
</div>
The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).
The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption
ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.
mine was DispatchQueue.main.sync inside the closer I made it DispatchQueue.main.async and it worked.
You are making it complicated. string
is already nullable. You don't need to make it more nullable. Take out the ?
on the property type.
The package nail
provides an enhanced mailx like interface. It includes the -r
option.
On Centos 5 installing the package mailx
gives you a program called mail
, which doesn't support the mailx
options.
With Windows 10 Insider build 17063 curl is available in the cmd and powershell since early 2018.
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
If your project (PrjTest) does not expose any public types within the PrjTest
namespace, it will cause that error.
Does the project (PrjTest) include any classes or types in the "PrjTest" namespace which are public?
I just use Number()
:
var i=2;
var j=3;
var k = Number(i) + Number(j); // 5
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT
. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
If you are using node.js, you can use unique-random-array. It simply picks something random from an array.
The way I build CMake projects cross platform is the following:
/project-root> mkdir build
/project-root> cd build
/project-root/build> cmake -G "<generator>" -DCMAKE_INSTALL_PREFIX=stage ..
/project-root/build> cmake --build . --target=install --config=Release
./project-root/build/stage
- the path is always considered relative to the current directory if it is not absolute).
with the buildsystem configured in the line before. It will execute the install
target which also builds all necessary dependent targets if they need to be built and then copies the files into the CMAKE_INSTALL_PREFIX
(which in this case is ./project-root/build/stage
. For multi-configuration builds, like in Visual Studio, you can also specify the configuration with the optional --config <config>
flag.cmake --build
command is that it works for all generators (i.e. makefiles and Visual Studio) without needing different commands.Afterwards I use the installed files to create packages or include them in other projects...
I put mine in /Developer/SDKs I had to authenticate to do that…but since there's no consensus I thought that it sounded like a place I'd remember.
GridLinked posted a PubSub solution which seems to be designed pretty well. The service can be found, here.
Also a diagram of their service:
Here's how to do it from a csv:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
# Load data from CSV
dat = np.genfromtxt('dat.xyz', delimiter=' ',skip_header=0)
X_dat = dat[:,0]
Y_dat = dat[:,1]
Z_dat = dat[:,2]
# Convert from pandas dataframes to numpy arrays
X, Y, Z, = np.array([]), np.array([]), np.array([])
for i in range(len(X_dat)):
X = np.append(X, X_dat[i])
Y = np.append(Y, Y_dat[i])
Z = np.append(Z, Z_dat[i])
# create x-y points to be used in heatmap
xi = np.linspace(X.min(), X.max(), 1000)
yi = np.linspace(Y.min(), Y.max(), 1000)
# Interpolate for plotting
zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')
# I control the range of my colorbar by removing data
# outside of my range of interest
zmin = 3
zmax = 12
zi[(zi<zmin) | (zi>zmax)] = None
# Create the contour plot
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
vmax=zmax, vmin=zmin)
plt.colorbar()
plt.show()
where dat.xyz
is in the form
x1 y1 z1
x2 y2 z2
...
If this is a file, you can simply skip the first and last lines and read the rest with csv
:
>>> s = """OK SYS 10 LEN 20 12 43
... 1233a.fdads.txt,23 /data/a11134/a.txt
... 3232b.ddsss.txt,32 /data/d13f11/b.txt
... 3452d.dsasa.txt,1234 /data/c13af4/f.txt
... ."""
>>> stream = StringIO.StringIO(s)
>>> rows = [row for row in csv.reader(stream,delimiter=',') if len(row) == 2]
>>> rows
[['1233a.fdads.txt', '23 /data/a11134/a.txt'], ['3232b.ddsss.txt', '32 /data/d13f11/b.txt'], ['3452d.dsasa.txt', '1234 /data/c13af4/f.txt']]
If its a file, then you can do this:
with open('myfile.txt','r') as f:
rows = [row for row in csv.reader(f,delimiter=',') if len(row) == 2]
__tests__
folderYou could add a .eslintrc.yml
file in your __tests__
folders, that extends you basic configuration:
extends: <relative_path to .eslintrc>
env:
jest: true
If you have only one __tests__
folder, this solution is the best since it scope jest environment only where it is needed.
If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:
#!/usr/bin/env zsh
for folder in **/__tests__/ ;do
count=$(($(tr -cd '/' <<< $folder | wc -c)))
echo $folder : $count
cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
jest: true
EOF
done
This script will look for __tests__
folders and add a .eslintrc.yml
file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc
.
Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.
One way to do the following without using JavaScript is via a technique called Faux-Columns.
It basically involves applying a background-image
to the parent elements of the floated elements which makes you believe that the two elements are the same height.
More information available at:
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
signingConfigs should be before buildTypes
signingConfigs {
debug {
storeFile file("debug.keystore")
}
myConfig {
storeFile file("other.keystore")
storePassword "android"
keyAlias "androidotherkey"
keyPassword "android"
}
}
buildTypes {
bar {
debuggable true
jniDebugBuild true
signingConfig signingConfigs.debug
}
foo {
debuggable false
jniDebugBuild false
signingConfig signingConfigs.myConfig
}
}
I created this regex according to RFC guidelines:
^[\\w\\.\\!_\\%#\\$\\&\\'=\\?\\*\\+\\-\\/\\^\\`\\{\\|\\}\\~]+@(?:\\w+\\.(?:\\w+\\-?)*)+$
I also had an issue on a site I was working on last week. I implemented a like box and tested the like box. Then I went ahead to add an image to my header (the ob:image meta). Still the correct image did not show up on my facebook notification.
I tried everything, and came to the conclusion that every single implementation of a like button is cached. So let's say you clock the Like button on url A, then you specify an image in the header and you test it by clicking the Luke button again on url A. You won't see the image as the page is cached. The image will show up when you click on the Like button on page B.
To reset the cache, you have to use the lint debugger tool that's mentioned above, and validate all the Urls for those that are cached... That's the only thing that worked for me.
Or if you want to do this with a script:
sed -i 's/\r//' filename
The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the reflog...
git reflog
and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the --hard
option).
Suppose the old commit was HEAD@{5}
in the ref log:
git reset --hard HEAD@{5}
In Windows, you may need to quote the reference:
git reset --hard "HEAD@{5}"
You can check the history of the candidate old head by just doing a git log HEAD@{5}
(Windows: git log "HEAD@{5}"
).
If you've not disabled per branch reflogs you should be able to simply do git reflog branchname@{1}
as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.
Per default, all reflogs are activated for non-bare repositories:
[core]
logAllRefUpdates = true
If array
is null
, trying to derefrence array.Length
will throw a NullReferenceException
. If your code considers null
to be an invalid value for array
, you should reject it and blame the caller. One such pattern is to throw ArgumentNullException
:
void MyMethod(string[] array)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (array.Length > 0)
{
// Do something with array…
}
}
If you want to accept a null
array as an indication to not do something or as an optional parameter, you may simply not access it if it is null:
void MyMethod(string[] array)
{
if (array != null)
{
// Do something with array here…
}
}
If you want to avoid touching array
when it is either null
or has zero length, then you can check for both at the same time with C#-6’s null coalescing operator.
void MyMethod(string[] array)
{
if (array?.Length > 0)
{
// Do something with array…
}
}
It seems strange that you are treating the empty array as a special case. In many cases, if you, e.g., would just loop over the array anyway, there’s no need to treat the empty array as a special case. foreach (var elem in array) {«body»}
will simply never execute «body»
when array.Length
is 0
. If you are treating array == null || array.Length == 0
specially to, e.g., improve performance, you might consider leaving a comment for posterity. Otherwise, the check for Length == 0
appears superfluous.
Superfluous code makes understanding a program harder because people reading the code likely assume that each line is necessary to solve some problem or achieve correctness. If you include unnecessary code, the readers are going to spend forever trying to figure out why that line is or was necessary before deleting it ;-).
Javascript has built in trim:
str.trim()
It doesn't work in IE8. If you have to support older browsers, use Tuxmentat's or Paul's answer.
You can like this...
document.getElementById('my-image').ondragstart = function() { return false; };
See it working (or not working, rather)
It seems you are using jQuery.
$('img').on('dragstart', function(event) { event.preventDefault(); });
You can use nircmd
project here: http://www.nirsoft.net/utils/nircmd.html
Example code:
nircmd win move ititle "cmd.exe" 5 5 10 10
nircmd win setsize ititle "cmd.exe" 30 30 100 200
nircmd cmdwait 1000 win setsize ititle "cmd.exe" 30 30 1000 600
easy replace
sed -i 's/utf8mb4_unicode_520_ci/utf8mb4_unicode_ci/g' your_sql_file.sql
Java is always pass by value, not pass by reference
First of all, we need to understand what pass by value and pass by reference are.
Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.
Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.
Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:
public class PassByValue {
public static void main(String[] args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeValue(t);
System.out.println(t.name);
}
public void changeValue(Test f) {
f.name = "changevalue";
}
}
class Test {
String name;
}
The output of this program is:
changevalue Let's understand step by step:
Test t = new Test(); As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .
first illustration
new PassByValue().changeValue(t);
When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.
second illustration
If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.
To understand this more clearly, consider the following example:
public class PassByValue {
public static void main(String[] args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeRefence(t);
System.out.println(t.name);
}
public void changeRefence(Test f) {
f = null;
}
}
class Test {
String name;
}
Will this throw a NullPointerException? No, because it only passes a copy of the reference. In the case of passing by reference, it could have thrown a NullPointerException, as seen below:
third illustration
Hopefully this will help.
My problem is almost similar. I have uncommitted files before I enter git reset --hard
.
Thankfully. I managed to skip all these resources. After I noticed that I can just undo (ctrl-z
). I just want to add this to all of the answers above.
Note. Its not possible to ctrl-z
unopened files.
@-webkit-keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.0; }
100% { opacity: 1.0; }
}
@-webkit-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
.blink {_x000D_
width: 10px;_x000D_
height: 10px;_x000D_
border-radius: 10px;_x000D_
animation: blinker 2s linear infinite;_x000D_
background-color: red;_x000D_
margin-right: 5px;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: center;_x000D_
}
_x000D_
<div class="content">_x000D_
<i class="blink"></i>_x000D_
LIVE_x000D_
</div>
_x000D_
If you have content with height unknown but you know the height the of container. The following solution works extremely well.
HTML
<div class="center-test">
<span></span><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Nesciunt obcaecati maiores nulla praesentium amet explicabo ex iste asperiores
nisi porro sequi eaque rerum necessitatibus molestias architecto eum velit
recusandae ratione.</p>
</div>
CSS
.center-test {
width: 300px;
height: 300px;
text-align:
center;
background-color: #333;
}
.center-test span {
height: 300px;
display: inline-block;
zoom: 1;
*display: inline;
vertical-align: middle;
}
.center-test p {
display: inline-block;
zoom: 1;
*display: inline;
vertical-align: middle;
color: #fff;
}
EXAMPLE http://jsfiddle.net/thenewconfection/eYtVN/
One gotcha for newby's to display: inline-block; [span] and [p] have no html white space so that the span then doesn't take up any space. Also I've added in the CSS hack for display inline-block for IE. Hope this helps someone!
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
To get the currently logged in user:
System.getProperty("user.name"); //platform independent
and the hostname of the machine:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
Bottom line at the top: Get newer programs or get an older computer.
The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.
The way I've done this is as follows...
condition = True
while condition:
do_stuff()
condition = (<something that evaluates to True or False>)
This seems to me to be the simplistic solution, I'm surprised I haven't seen it here already. This can obviously also be inverted to
while not condition:
etc.
Please use the below code
string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);
I didn't know you could do that with cp.
You can do it with mkdir ..
mkdir -p /var/path/to/your/dir
EDIT See lhunath's answer for incorporating cp.
Yes, it is possible. Try this:
body { background-image:
url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='%23F00'/><stop offset='90%' stop-color='%23fcc'/> </linearGradient><rect fill='url(%23gradient)' x='0' y='0' width='100%' height='100%'/></svg>");
}
(Note that the SVG content needs to be url-escaped for this to work, e.g. #
gets replaced with %23
.)
This works in IE 9 (which supports SVG). Data-URLs work in older versions of IE too (with limitations), but they don’t natively support SVG.
I was having the same problem, none of the posted solutions helped. Finally, I figured out what I was doing wrong. When I installed the Java JDK it asked me for a directiy where I wanted to install. I changed the directory to where I wanted the code to go. It then asked for a directory where it could install the Runtime Environment and I selected the SAME DIRECTORY where I installed the JDK. It over wrote my lib folder and erased the tools.jar. Be sure to use different folders during the install. I used my custom folder for the JDK and the default folder for the RE and everything worked fine.
You may wish to also consider the class java.util.concurrent.FutureTask
.
If you are using Java 5 or later, FutureTask is a turnkey implementation of "A cancellable asynchronous computation."
There are even richer asynchronous execution scheduling behaviors available in the java.util.concurrent
package (for example, ScheduledExecutorService
), but FutureTask
may have all the functionality you require.
I would even go so far as to say that it is no longer advisable to use the first code pattern you gave as an example ever since FutureTask
became available. (Assuming you are on Java 5 or later.)
Here's my solution if you are using typescript in a functional way:
const hasDuplicates = <T>(arr: T[]): boolean => {
if (arr.length === 0) return false
if (arr.lastIndexOf(arr[0]) !== 0) return true
return hasDuplicates(arr.slice(1))
}
1. Open "Turn windows features on or off" by: WinKey+ R => "optionalfeatures" => OK
Tested on Win 10 - But probably will work on other windows versions as well.
You need to instantiate a class instance here.
Use
p = Pump()
p.getPumps()
Small example -
>>> class TestClass:
def __init__(self):
print("in init")
def testFunc(self):
print("in Test Func")
>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func
Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?
In PHP any date can be converted into the required date format using different scenarios for example to change any date format into Day, Date Month Year
$newdate = date("D, d M Y", strtotime($date));
It will show date in the following very well format
Mon, 16 Nov 2020
If you are using Selenium web driver with Python, you can use PyVirtualDisplay, a Python wrapper for Xvfb and Xephyr.
PyVirtualDisplay needs Xvfb as a dependency. On Ubuntu, first install Xvfb:
sudo apt-get install xvfb
Then install PyVirtualDisplay from PyPI:
pip install pyvirtualdisplay
Sample Selenium script in Python in a headless mode with PyVirtualDisplay:
#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# Now Firefox will run in a virtual display.
# You will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
EDIT
The initial answer was posted in 2014 and now we are at the cusp of 2018. Like everything else, browsers have also advanced. Chrome has a completely headless version now which eliminates the need to use any third-party libraries to hide the UI window. Sample code is as follows:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
chrome_options=chrome_options
)
driver.get("https://www.google.com")
driver.get_screenshot_as_file("capture.png")
driver.close()
Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE_" is 7 characters... ? If so, change the 8 below to 7)
from glob import glob
from os import rename
for fname in glob('*.prj'):
rename(fname, fname[8:])
Thank you guys for the help,
When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:
Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
var sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]
Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.
var objSorted = {}
sortable.forEach(function(item){
objSorted[item[0]]=item[1]
})
In ES8, you can use Object.entries()
to convert the object into an array:
const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.entries(maxSpeed)
.sort(([,a],[,b]) => a-b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log(sortable);
_x000D_
In ES10, you can use Object.fromEntries()
to convert array to object. Then the code can be simplified to this:
const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.fromEntries(
Object.entries(maxSpeed).sort(([,a],[,b]) => a-b)
);
console.log(sortable);
_x000D_
hive --version
hadoop version
If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...
Should do the job for MySQL, for SqlServer I'm sure there is an analog function.
If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE
for MySQL.