Reading JSON from a file?
In python 3, we can use below method.
Read from file and convert to JSON
import json
from pprint import pprint
# Considering "json_list.json" is a json file
with open('json_list.json') as fd:
json_data = json.load(fd)
pprint(json_data)
with statement automatically close the opened file descriptor.
String to JSON
import json
from pprint import pprint
json_data = json.loads('{"name" : "myName", "age":24}')
pprint(json_data)
How to set default values in Go structs
Force a method to get the struct (the constructor way).
From this post:
A good design is to make your type unexported, but provide an exported constructor function like NewMyType()
in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.
This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.
Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.
How can I get a specific field of a csv file?
#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.
USAGE:
%prog csv_filename row_number column_number
"""
import csv
import sys
filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]
with open(filename, 'rb') as f:
rows = list(csv.reader(f))
print rows[row_number][column_number]
Example
$ python print-csv-field.py input.csv 2 2
ddddd
Note: list(csv.reader(f))
loads the whole file in memory. To avoid that you could use itertools
:
import itertools
# ...
with open(filename, 'rb') as f:
row = next(itertools.islice(csv.reader(f), row_number, row_number+1))
print row[column_number]
Issue pushing new code in Github
Assuming that you added the Readme.md file through the interface provided by github, the readme is not yet in your local folder. Hence, when you try to push to the remote repo, you get an error, because your local repo is lacking the readme file - it's "behind the times", so to speak. Hence, as is suggested in the error message, try "git pull" first. This will pull the readme from the remote repository and merge it with your local directory. After that, you should have no problem pushing to the remote repo (the commands you posted look valid to me).
Calculate difference in keys contained in two Python dictionaries
If on Python = 2.7:
# update different values in dictB
# I would assume only dictA should be updated,
# but the question specifies otherwise
for k in dictA.viewkeys() & dictB.viewkeys():
if dictA[k] != dictB[k]:
dictB[k]= dictA[k]
# add missing keys to dictA
dictA.update( (k,dictB[k]) for k in dictB.viewkeys() - dictA.viewkeys() )
How to delete Tkinter widgets from a window?
You simply use the destroy()
method to delete the specified widgets like this:
lbl = tk.Label(....)
btn = tk.Button(....., command=lambda: lbl.destroy())
Using this you can completely destroy the specific widgets.
CSS: fixed to bottom and centered
I ran into a problem where the typical position: fixed
and bottom: 0
didn't work. Discovered a neat functionality with position: sticky
. Note it's "relatively" new so it won't with IE/Edge 15 and earlier.
Here's an example for w3schools.
_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
<style>
div.sticky {
position: sticky;
bottom: 0;
background-color: yellow;
padding: 30px;
font-size: 20px;
}
</style>
</head>
<body>
<p>Lorem ipsum dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas </p>
<div class="sticky">I will stick to the screen when you reach my scroll position</div>
</body>
</html>
_x000D_
_x000D_
_x000D_
Why does Java have transient fields?
A field which is declare with transient modifier it will not take part in serialized process.
When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.
Export JAR with Netbeans
You need to enable the option
Project Properties -> Build -> Packaging -> Build JAR after compiling
(but this is enabled by default)
Big O, how do you calculate/approximate it?
Basically the thing that crops up 90% of the time is just analyzing loops. Do you have single, double, triple nested loops? The you have O(n), O(n^2), O(n^3) running time.
Very rarely (unless you are writing a platform with an extensive base library (like for instance, the .NET BCL, or C++'s STL) you will encounter anything that is more difficult than just looking at your loops (for statements, while, goto, etc...)
Get date from input form within PHP
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
How can I write a regex which matches non greedy?
The non-greedy ?
works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .
. You need to tell them explicitly that you want to match line-breaks too with .
For example,
<img\s.*?>
works fine!
Check the results here.
Also, read about how dot behaves in various regex flavours.
Why emulator is very slow in Android Studio?
A quick fix if using Android Studio (or Eclipse) is to disable the boot animation.
1) Select Run > Edit Configurations
2) Android Application > YOURAPP
3) Select the "Emulator" tab and check the "Disable boot animation"
This is will stop the "ANDROID" image from loading and boot directly to the lock screen, then keep your the emulator open. Also, to avoid problems, don't rotate the device before launch (Cmnd + Ctrl + F11), and don't try to run the app more than once during installation.
Remove a modified file from pull request
A pull request is just that: a request to merge one branch into another.
Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".
The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.
In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p
should sort you out.
How do I import global modules in Node? I get "Error: Cannot find module <module>"?
Node.js uses the environmental variable NODE_PATH
to allow for specifying additional directories to include in the module search path. You can use npm
itself to tell you where global modules are stored with the npm root -g
command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)
export NODE_PATH=$(npm root --quiet -g)
What is setBounds and how do I use it?
here's a short paragraph from this article How to Make Frames (Main Windows) - The Java Tutorials - Oracle that explains what setBounds method does in addition to some other similar methods:
The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
the parameters of setBounds are (int x, int y, int width, int height)
x and y are define the position/location and width and height define the size/dimension of the frame.
FPDF utf-8 encoding (HOW-TO)
there is a really simple solution for this problem.
In the file fpdf.php go to the line that says:
if($txt!=='')
{
It is line 648 in my version of fpdf.
Insert the following line of code:
$txt = iconv('utf-8', 'cp1252', $txt);
(above the line of code)
if($align=='R')
This works for all German special characters and should also work for Greek special characters. Otherwise simply replace cp1252 with the respective alphabet you require. You can see all supported characters here: http://en.wikipedia.org/wiki/Windows-1252
I saw the solution here: http://fudforum.org/forum/index.php?t=msg&goto=167345
Please use my example code above, as the original author forgot to insert a dash between utf and 8.
Hope the above was helpful.
Daan
Having trouble setting working directory
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
- In the bottom right window move the tab over to 'files'.
- Navigate through there to whichever folder you were planning to use as your working directory.
- Under 'more' click 'set as working directory'
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
How to remove jar file from local maven repository which was added with install:install-file?
Although deleting files manually works, there is an official way of removing dependencies of your project from your local (cache) repository and optionally re-resolving them from remote repositories.
The goal purge-local-repository
, on the standard Maven dependency plugin, will remove the locally installed dependencies of this project from your cache. Optionally, you may re-resolve them from the remote repositories at the same time.
This should be used as part of a project phase because it applies to the dependencies for the containing project. Also transitive dependencies will be purged (locally) as well, by default.
If you want to explicitly remove a single artifact from the cache, use purge-local-repository
with the manualInclude
parameter. For example, from the command line:
mvn dependency:purge-local-repository -DmanualInclude="groupId:artifactId, ..."
The documentation implies that this does not remove transitive dependencies by default. If you are running with a non-standard cache location, or on multiple platforms, these are more reliable than deleting files "by hand".
The full documentation is in the maven-dependency-plugin spec.
Note: Older versions of the maven dependency
plugin had a manual-purge-local-repository
goal, which is now (version 2.8) implied by the use of manualInclude
. The documentation for manualIncludes
(with an s
) should be read as well.
Open popup and refresh parent page on close popup
on your child page, put these:
<script type="text/javascript">
function refreshAndClose() {
window.opener.location.reload(true);
window.close();
}
</script>
and
<body onbeforeunload="refreshAndClose();">
but as a good UI design, you should use a Close button
because it's more user friendly. see code below.
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
window.opener.location.reload(true);
window.close();
});
});
</script>
<input type='button' id='btn' value='Close' />
Get height of div with no height set in css
Just a note in case others have the same problem.
I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().
var currentHeight = 0;
$(window).load(function() {
//get the natural page height -set it in variable above.
currentHeight = $('#js_content_container').outerHeight();
console.log("set current height on load = " + currentHeight)
console.log("content height function (should be 374) = " + contentHeight());
});
How to connect TFS in Visual Studio code
It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".
Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Notification not showing in Oreo
CHANNEL_ID
in NotificationChannel and Notification.Builder must be the same, try this code:
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Solveta Unread", NotificationManager.IMPORTANCE_DEFAULT);
Notification.Builder notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
Datatables on-the-fly resizing
The code below is the combination of Chintan Panchal's answer along with Antoine Leclair's comment (placing the code in the windows resize event). (I didn't need the debounce mentioned by Antoine Leclair, however that could be a best practice.)
$(window).resize( function() {
$("#example").DataTable().columns.adjust().draw();
});
This was the approach that worked in my case.
Check if table exists
DatabaseMetaData dbm = con.getMetaData();
// check if "employee" table is there
ResultSet tables = dbm.getTables(null, null, "employee", null);
if (tables.next()) {
// Table exists
}
else {
// Table does not exist
}
How can I pass arguments to anonymous functions in JavaScript?
What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).
Why is setState in reactjs Async instead of Sync?
setState is asynchronous. You can see in this documentation by Reactjs
React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.
However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.
The reason is this would break the consistency between props and state, causing issues that are very hard to debug.
You can still perform functions if it is dependent on the change of the state value:
Option 1:
Using callback function with setState
this.setState({
value: newValue
},()=>{
// It is an callback function.
// Here you can access the update value
console.log(this.state.value)
})
Option 2: using componentDidUpdate
This function will be called whenever the state of that particular class changes.
componentDidUpdate(prevProps, prevState){
//Here you can check if value of your desired variable is same or not.
if(this.state.value !== prevState.value){
// this part will execute if your desired variable updates
}
}
Maximum length for MySQL type text
For the MySql version 8.0.
Numeric Type Storage Requirements
Data Type Storage Required
TINYINT 1 byte
SMALLINT 2 bytes
MEDIUMINT 3 bytes
INT, INTEGER 4 bytes
BIGINT 8 bytes
FLOAT(p) 4 bytes if 0 <= p <= 24, 8 bytes if 25 <= p <= 53
FLOAT 4 bytes
DOUBLE, REAL 8 bytes
DECIMAL(M,D), NUMERIC(M,D) Varies; see following discussion
BIT(M) approximately (M+7)/8 bytes
Values for DECIMAL (and NUMERIC) columns are represented using a binary format that packs nine decimal (base 10) digits into four bytes. Storage for the integer and fractional parts of each value are determined separately. Each multiple of nine digits requires four bytes, and the “leftover” digits require some fraction of four bytes. The storage required for excess digits is given by the following table.
Date and Time Type Storage Requirements
For TIME, DATETIME, and TIMESTAMP columns, the storage required for tables created before MySQL 5.6.4 differs from tables created from 5.6.4 on. This is due to a change in 5.6.4 that permits these types to have a fractional part, which requires from 0 to 3 bytes.
Data Type Storage Required Before MySQL 5.6.4 Storage Required as of MySQL 5.6.4
YEAR 1 byte 1 byte
DATE 3 bytes 3 bytes
TIME 3 bytes 3 bytes + fractional seconds storage
DATETIME 8 bytes 5 bytes + fractional seconds storage
TIMESTAMP 4 bytes 4 bytes + fractional seconds storage
As of MySQL 5.6.4, storage for YEAR and DATE remains unchanged. However, TIME, DATETIME, and TIMESTAMP are represented differently. DATETIME is packed more efficiently, requiring 5 rather than 8 bytes for the nonfractional part, and all three parts have a fractional part that requires from 0 to 3 bytes, depending on the fractional seconds precision of stored values.
Fractional Seconds Precision Storage Required
0 0 bytes
1, 2 1 byte
3, 4 2 bytes
5, 6 3 bytes
For example, TIME(0), TIME(2), TIME(4), and TIME(6) use 3, 4, 5, and 6 bytes, respectively. TIME and TIME(0) are equivalent and require the same storage.
For details about internal representation of temporal values, see MySQL Internals: Important Algorithms and Structures.
String Type Storage Requirements
In the following table, M represents the declared column length in characters for nonbinary string types and bytes for binary string types. L represents the actual length in bytes of a given string value.
Data Type Storage Required
CHAR(M) The compact family of InnoDB row formats optimize storage for variable-length character sets. See COMPACT Row Format Characteristics. Otherwise, M × w bytes, <= M <= 255, where w is the number of bytes required for the maximum-length character in the character set.
BINARY(M) M bytes, 0 <= M <= 255
VARCHAR(M), VARBINARY(M) L + 1 bytes if column values require 0 - 255 bytes, L + 2 bytes if values may require more than 255 bytes
TINYBLOB, TINYTEXT L + 1 bytes, where L < 28
BLOB, TEXT L + 2 bytes, where L < 216
MEDIUMBLOB, MEDIUMTEXT L + 3 bytes, where L < 224
LONGBLOB, LONGTEXT L + 4 bytes, where L < 232
ENUM('value1','value2',...) 1 or 2 bytes, depending on the number of enumeration values (65,535 values maximum)
SET('value1','value2',...) 1, 2, 3, 4, or 8 bytes, depending on the number of set members (64 members maximum)
Gray out image with CSS?
Use the CSS3 filter property:
img {
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-o-filter: grayscale(100%);
-ms-filter: grayscale(100%);
filter: grayscale(100%);
}
The browser support is a little bad but it's 100% CSS. A nice article about the CSS3 filter property you can find here: http://blog.nmsdvid.com/css-filter-property/
How to remove and clear all localStorage data
Something like this should do:
function cleanLocalStorage() {
for(key in localStorage) {
delete localStorage[key];
}
}
Be careful about using this, though, as the user may have other data stored in localStorage
and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage
or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage
.
Edit: As Lyn pointed out, you'll be good with localStorage.clear()
. My previous points still stand, however.
How To Define a JPA Repository Query with a Join
You are experiencing this issue for two reasons.
- The JPQL Query is not valid.
- You have not created an association between your entities that the underlying JPQL query can utilize.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
How to extract the year from a Python datetime object?
It's in fact almost the same in Python.. :-)
import datetime
year = datetime.date.today().year
Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:
import datetime
year = datetime.datetime.today().year
(Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).
One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.
Func delegate with no return type
A very easy way to invoke return and non return value subroutines. is using Func and Action respectively. (see also https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx)
Try this this example
using System;
public class Program
{
private Func<string,string> FunctionPTR = null;
private Func<string,string, string> FunctionPTR1 = null;
private Action<object> ProcedurePTR = null;
private string Display(string message)
{
Console.WriteLine(message);
return null;
}
private string Display(string message1,string message2)
{
Console.WriteLine(message1);
Console.WriteLine(message2);
return null;
}
public void ObjectProcess(object param)
{
if (param == null)
{
throw new ArgumentNullException("Parameter is null or missing");
}
else
{
Console.WriteLine("Object is valid");
}
}
public void Main(string[] args)
{
FunctionPTR = Display;
FunctionPTR1= Display;
ProcedurePTR = ObjectProcess;
FunctionPTR("Welcome to function pointer sample.");
FunctionPTR1("Welcome","This is function pointer sample");
ProcedurePTR(new object());
}
}
Why do people write #!/usr/bin/env python on the first line of a Python script?
Expanding a bit on the other answers, here's a little example of how your command line scripts can get into trouble by incautious use of /usr/bin/env
shebang lines:
$ /usr/local/bin/python -V
Python 2.6.4
$ /usr/bin/python -V
Python 2.5.1
$ cat my_script.py
#!/usr/bin/env python
import json
print "hello, json"
$ PATH=/usr/local/bin:/usr/bin
$ ./my_script.py
hello, json
$ PATH=/usr/bin:/usr/local/bin
$ ./my_script.py
Traceback (most recent call last):
File "./my_script.py", line 2, in <module>
import json
ImportError: No module named json
The json module doesn't exist in Python 2.5.
One way to guard against that kind of problem is to use the versioned python command names that are typically installed with most Pythons:
$ cat my_script.py
#!/usr/bin/env python2.6
import json
print "hello, json"
If you just need to distinguish between Python 2.x and Python 3.x, recent releases of Python 3 also provide a python3
name:
$ cat my_script.py
#!/usr/bin/env python3
import json
print("hello, json")
Use of 'const' for function parameters
Sometimes (too often!) I have to untangle someone else's C++ code. And we all know that someone else's C++ code is a complete mess almost by definition :) So the first thing I do to decipher local data flow is put const in every variable definition until compiler starts barking. This means const-qualifying value arguments as well, because they are just fancy local variables initialized by caller.
Ah, I wish variables were const by default and mutable was required for non-const variables :)
C# importing class into another class doesn't work
using
is used for importing namespaces not classes.
So if your class is in namespace X
namespace X
{
public class MyClass {
void stuff() {
}
}
}
then to use it in another namespace where you want it
using System;
using X;
public class MyMainClass {
static void Main() {
MyClass test = new MyClass();
}
}
Using new line(\n) in string and rendering the same in HTML
You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var display_txt = "1st line text" +"\n" + "2nd line text";
$('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>
<pre>
<p id="somediv"></p>
</pre>
</body>
</html>
ASP.NET MVC View Engine Comparison
My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.
To provide a simple sample:
@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>
And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.
As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.
Thanks
Nathj07
Query an XDocument for elements by name at any depth
This my variant of the solution based on LINQ and the Descendants method of the XDocument
class
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument xml = XDocument.Parse(@"
<root>
<child id='1'/>
<child id='2'>
<subChild id='3'>
<extChild id='5' />
<extChild id='6' />
</subChild>
<subChild id='4'>
<extChild id='7' />
</subChild>
</child>
</root>");
xml.Descendants().Where(p => p.Name.LocalName == "extChild")
.ToList()
.ForEach(e => Console.WriteLine(e));
Console.ReadLine();
}
}
Results:
For more details on the Desendants
method take a look here.
Install php-mcrypt on CentOS 6
If php_mcrypt installed on 64bit but reported missing by an installer, check the extension path:
vi /etc/php.d/mcrypt.ini
; Enable mcrypt extension module
;extension=module.so
extension=/usr/lib64/php/modules/mcrypt.so
concat scope variables into string in angular directive expression
It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.
In general, I suggest calling a function on ng-click like so:
<a ng-click="navigateToPath()">click me</a>
obj.val1
& obj.val2
should be available on your controller's $scope, you dont need to pass those into a function from the markup.
then, in your controller:
$scope.navigateToPath = function(){
var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
$location.path(path)
}
Min / Max Validator in Angular 2 Final
In latest Angular versions, min and max are already added. Here is the link:
https://angular.io/api/forms/Validators#max
This is how I used Max validator in my project:
<mat-form-field class="globalInput">
<input (change)="CalculateAmount()" matInput placeholder="Quantity" name="productQuantity" type="number" [formControl]="quantityFormControl">
</mat-form-field>
<mat-error *ngIf="quantityFormControl.hasError('max')">
Only <strong>{{productQuantity}}</strong> available!
</mat-error>
Initialize the form control and add the validator in the component:
quantityFormControl = new FormControl('', Validators.max(15));
You can also set validator dynamically on an event like this:
quantityFormControl = new FormControl();
OnProductSelected(){
this.quantityFormControl.setValidators(Validators.max(this.someVariable));
}
Hope it helps.
How can I create a temp file with a specific extension with .NET?
The MSDN documentation for C++'s GetTempFileName discusses your concern and answers it:
GetTempFileName is not able to guarantee that the file name is unique.
Only the lower 16 bits of the uUnique parameter are used. This limits GetTempFileName to a maximum of 65,535 unique file names if the lpPathName and lpPrefixString parameters remain the same.
Due to the algorithm used to generate file names, GetTempFileName can perform poorly when creating a large number of files with the same prefix. In such cases, it is recommended that you construct unique file names based on GUIDs.
Mount current directory as a volume in Docker on Windows 10
- Open Settings on Docker Desktop (Docker for Windows).
- Select Shared Drives.
- Select the drive that you want to use inside your containers (e.g., C).
Click Apply. You may be asked to provide user credentials.
The command below should now work on PowerShell (command prompt does not support ${PWD}
):
docker run --rm -v ${PWD}:/data alpine ls /data
IMPORTANT: if/when you change your Windows domain password, the mount will stop working silently, that is, -v
will work but the container will not see your host folders and files. Solution: go back to Settings, uncheck the shared drives, Apply, check them again, Apply, and enter the new password when prompted.
Use StringFormat to add a string to a WPF XAML binding
In xaml
<TextBlock Text="{Binding CelsiusTemp}" />
In ViewModel
, this way setting the value also works:
public string CelsiusTemp
{
get { return string.Format("{0}°C", _CelsiusTemp); }
set
{
value = value.Replace("°C", "");
_CelsiusTemp = value;
}
}
ActionLink htmlAttributes
@Html.ActionLink("display name", "action", "Contorller"
new { id = 1 },Html Attribute=new {Attribute1="value"})
How do I install Java on Mac OSX allowing version switching?
You can use asdf to install and switch between multiple java versions. It has plugins for other languages as well. You can install asdf with Homebrew
brew install asdf
When asdf is configured, install java plugin
asdf plugin-add java
Pick a version to install
asdf list-all java
For example to install and configure adoptopenjdk8
asdf install java adoptopenjdk-8.0.272+10
asdf global java adoptopenjdk-8.0.272+10
And finally if needed, configure JAVA_HOME for your shell. Just add to your shell init script such as ~/.zshrc in case of zsh:
. ~/.asdf/plugins/java/set-java-home.zsh
How to make Visual Studio copy a DLL file to the output directory?
xcopy /y /d "$(ProjectDir)External\*.dll" "$(TargetDir)"
You can also refer to a relative path, the next example will find the DLL in a folder located one level above the project folder. If you have multiple projects that use the DLL in a single solution, this places the source of the DLL in a common area reachable when you set any of them as the Startup Project.
xcopy /y /d "$(ProjectDir)..\External\*.dll" "$(TargetDir)"
The /y
option copies without confirmation.
The /d
option checks to see if a file exists in the target and if it does only copies if the source has a newer timestamp than the target.
I found that in at least newer versions of Visual Studio, such as VS2109, $(ProjDir)
is undefined and had to use $(ProjectDir)
instead.
Leaving out a target folder in xcopy
should default to the output directory. That is important to understand reason $(OutDir)
alone is not helpful.
$(OutDir)
, at least in recent versions of Visual Studio, is defined as a relative path to the output folder, such as bin/x86/Debug
. Using it alone as the target will create a new set of folders starting from the project output folder. Ex: … bin/x86/Debug/bin/x86/Debug
.
Combining it with the project folder should get you to the proper place. Ex: $(ProjectDir)$(OutDir)
.
However $(TargetDir)
will provide the output directory in one step.
Microsoft's list of MSBuild macros for current and previous versions of Visual Studio
Html table with button on each row
Pretty sure this solves what you're looking for:
HTML:
<table>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
</table>
Javascript (using jQuery):
$(document).ready(function(){
$('.editbtn').click(function(){
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
Edit:
Apparently I should have looked at your sample code first ;)
You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.
By using classes, you can apply the same logic to multiple elements without any conflicts.
JSFiddle sample
Wampserver icon not going green fully, mysql services not starting up?
I was running on the same problem, wampmysqld64 did not start, so I checked the Mysql log which you should find it inside the main wamp64 folder, and I found all the details on why is not working. on my computer I found another mysql instance is running so it prevents the wampmysqld64 to start. I stopped the other instance, and everything works fine after.
What is the iPad user agent?
Mine says:
Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5
What's wrong with overridable method calls in constructors?
Here's an example which helps to understand this:
public class Main {
static abstract class A {
abstract void foo();
A() {
System.out.println("Constructing A");
foo();
}
}
static class C extends A {
C() {
System.out.println("Constructing C");
}
void foo() {
System.out.println("Using C");
}
}
public static void main(String[] args) {
C c = new C();
}
}
If you run this code, you get the following output:
Constructing A
Using C
Constructing C
You see? foo()
makes use of C before C's constructor has been run. If foo()
requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo()
expects, you get a warning.
correct PHP headers for pdf file download
Example 2 on w3schools shows what you are trying to achieve.
<?php
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
Also remember that,
It is important to notice that header() must be called before any
actual output is sent (In PHP 4 and later, you can use output
buffering to solve this problem)
git stash apply version
If one is on a Windows machine and in PowerShell, one needs to quote the argument such as:
git stash apply "stash@{0}"
...or to apply the changes and remove from the stash:
git stash pop "stash@{0}"
Otherwise without the quotes you might get this error:
fatal: ambiguous argument 'stash@': unknown revision or path not in
the working tree.
Escape quotes in JavaScript
Escape whitespace as well. It sounds to me like Firefox is assuming three arguments instead of one.
is the non-breaking space character. Even if it's not the whole problem, it may still be a good idea.
Hashmap holding different data types as values for instance Integer, String and Object
If you don't have Your own Data Class, then you can design your map as follows
Map<Integer, Object> map=new HashMap<Integer, Object>();
Here don't forget to use "instanceof" operator while retrieving the values from MAP.
If you have your own Data class then then you can design your map as follows
Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
Map<Integer,Demo> map=new HashMap<Integer, Demo>();
Demo d1= new Demo(1,"hi",new Date(),1,1);
Demo d2= new Demo(2,"this",new Date(),2,1);
Demo d3= new Demo(3,"is",new Date(),3,1);
Demo d4= new Demo(4,"mytest",new Date(),4,1);
//adding values to map
map.put(d1.getKey(), d1);
map.put(d2.getKey(), d2);
map.put(d3.getKey(), d3);
map.put(d4.getKey(), d4);
//retrieving values from map
Set<Integer> keySet= map.keySet();
for(int i:keySet){
System.out.println(map.get(i));
}
//searching key on map
System.out.println(map.containsKey(d1.getKey()));
//searching value on map
System.out.println(map.containsValue(d1));
}
}
class Demo{
private int key;
private String message;
private Date time;
private int count;
private int version;
public Demo(int key,String message, Date time, int count, int version){
this.key=key;
this.message = message;
this.time = time;
this.count = count;
this.version = version;
}
public String getMessage() {
return message;
}
public Date getTime() {
return time;
}
public int getCount() {
return count;
}
public int getVersion() {
return version;
}
public int getKey() {
return key;
}
@Override
public String toString() {
return "Demo [message=" + message + ", time=" + time
+ ", count=" + count + ", version=" + version + "]";
}
}
Chrome disable SSL checking for sites?
In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.
I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?
Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,
There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.
The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).
Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.
Convert string to nullable type (int, double, etc...)
You can use the following with objects, unfortunately this does not work with strings though.
double? amount = (double?)someObject;
I use it for wrapping a session variable in a property (on a base page).. so my actual usage is (in my base page):
public int? OrganisationID
{
get { return (int?)Session[Constants.Session_Key_OrganisationID]; }
set { Session[Constants.Session_Key_OrganisationID] = value; }
}
I'm able to check for null in page logic:
if (base.OrganisationID == null)
// do stuff
Change directory in PowerShell
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
What is this: [Ljava.lang.Object;?
[Ljava.lang.Object;
is the name for Object[].class
, the java.lang.Class
representing the class of array of Object
.
The naming scheme is documented in Class.getName()
:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).
If this class object represents a primitive type or void
, then the name returned is the Java language keyword corresponding to the primitive type or void
.
If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '['
characters representing the depth of the array nesting.
The encoding of element type names is as follows:
Element Type Encoding
boolean Z
byte B
char C
double D
float F
int I
long J
short S
class or interface Lclassname;
Yours is the last on that list. Here are some examples:
// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx
The reason why the toString()
method on arrays returns String
in this format is because arrays do not @Override
the method inherited from Object
, which is specified as follows:
The toString
method for class Object
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Note: you can not rely on the toString()
of any arbitrary object to follow the above specification, since they can (and usually do) @Override
it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass()
on it (a final
method inherited from Object
) and then reflecting on the returned Class
object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).
On a more "useful" toString
for arrays
java.util.Arrays
provides toString
overloads for primitive arrays and Object[]
. There is also deepToString
that you may want to use for nested arrays.
Here are some examples:
int[] nums = { 1, 2, 3 };
System.out.println(nums);
// [I@xxxxx
System.out.println(Arrays.toString(nums));
// [1, 2, 3]
int[][] table = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]
System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]
There are also Arrays.equals
and Arrays.deepEquals
that perform array equality comparison by their elements, among many other array-related utility methods.
Related questions
Adding a new entry to the PATH variable in ZSH
Here, add this line to .zshrc
:
export PATH=/home/david/pear/bin:$PATH
EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH
. This approach is standard for bash
, but as far as I know, there is no reason to use it when ZSH provides better alternatives.
Iterating through directories with Python
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print
statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.
Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
git: diff between file in local repo and origin
I tried a couple of solution but I thing easy way like this (you are in the local folder):
#!/bin/bash
git fetch
var_local=`cat .git/refs/heads/master`
var_remote=`git log origin/master -1 | head -n1 | cut -d" " -f2`
if [ "$var_remote" = "$var_local" ]; then
echo "Strings are equal." #1
else
echo "Strings are not equal." #0 if you want
fi
Then you did compare local git and remote git last commit number....
Display TIFF image in all web browser
You can try converting your image from tiff to PNG, here is how to do it:
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;
public class ImgConvTiffToPng {
public static byte[] convert(byte[] tiff) throws Exception {
byte[] out = new byte[0];
InputStream inputStream = new ByteArrayInputStream(tiff);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
RenderedImage op = dec.decodeAsRenderedImage(0);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PNGEncodeParam jpgparam = null;
ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
en.encode(op);
outputStream = (ByteArrayOutputStream) en.getOutputStream();
out = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
return out;
}
Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo
I just tried with PHP 5.2, and that constant seems to exists :
var_dump(PDO::MYSQL_ATTR_INIT_COMMAND);
Gives me :
int 1002
But it seems there is a bug in PHP 5.3, that causes this constant to not exists anymore -- or, at least, not when the mysqlnd driver is used (and it's the one that's configured by default)
I suppose a temporary solution, as suggested on this bug report, could be to directly use the integer 1002
value, instead of the contant...
But note that you should go back to using the constant as soon as possible -- as this makes the code easier to understand.
How to search contents of multiple pdf files?
I had the same problem and thus I wrote a script which searches all pdf files in the specified folder for a string and prints the PDF files wich matched the query string.
Maybe this will be helpful to you.
You can download it here
Node.js on multi-core machines
You can use cluster module. Check this.
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
}
What is Dependency Injection?
I know there are already many answers, but I found this very helpful: http://tutorials.jenkov.com/dependency-injection/index.html
No Dependency:
public class MyDao {
protected DataSource dataSource = new DataSourceImpl(
"driver", "url", "user", "password");
//data access methods...
public Person readPerson(int primaryKey) {...}
}
Dependency:
public class MyDao {
protected DataSource dataSource = null;
public MyDao(String driver, String url, String user, String password) {
this.dataSource = new DataSourceImpl(driver, url, user, password);
}
//data access methods...
public Person readPerson(int primaryKey) {...}
}
Notice how the DataSourceImpl
instantiation is moved into a constructor. The constructor takes four parameters which are the four values needed by the DataSourceImpl
. Though the MyDao
class still depends on these four values, it no longer satisfies these dependencies itself. They are provided by whatever class creating a MyDao
instance.
How can I execute a python script from an html button?
Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it's more powerful.
Here is Step by guide to get complete your task :
pip install django
django-admin createproject buttonpython
then you have to create a file name views.py in buttonpython directory.
write below code in views.py:
from django.http import HttpResponse
def sample(request):
#your python script code
output=code output
return HttpResponse(output)
Once done navigate to urls.py and add this stanza
from . import views
path('', include('blog.urls')),
Now go to parent directory and execute manage.py
python manage.py runserver 127.0.0.1:8001
Step by Step Guide in Detail: Run Python script on clicking HTML button
Manipulating an Access database from Java without ODBC
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
Option 1: Using Maven
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
Option 2: Manually adding the JARs to your project
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. The UcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
That's it!
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
Disclosure
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
How to get the last char of a string in PHP?
As of PHP 7.1.0, negative string offsets are also supported.
So, if you keep up with the times, you can access the last character in the string like this:
$str[-1]
DEMO
At the request of a @mickmackusa, I supplement my answer with possible ways of application:
<?php
$str='abcdef';
var_dump($str[-2]); // => string(1) "e"
$str[-3]='.';
var_dump($str); // => string(6) "abc.ef"
var_dump(isset($str[-4])); // => bool(true)
var_dump(isset($str[-10])); // => bool(false)
Getting DOM elements by classname
There is also another approach without the use of DomXPath
or Zend_Dom_Query
.
Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.
function getElementsByClass(&$parentNode, $tagName, $className) {
$nodes=array();
$childNodeList = $parentNode->getElementsByTagName($tagName);
for ($i = 0; $i < $childNodeList->length; $i++) {
$temp = $childNodeList->item($i);
if (stripos($temp->getAttribute('class'), $className) !== false) {
$nodes[]=$temp;
}
}
return $nodes;
}
suppose you have a variable $html
the following HTML:
<html>
<body>
<div id="content_node">
<p class="a">I am in the content node.</p>
<p class="a">I am in the content node.</p>
<p class="a">I am in the content node.</p>
</div>
<div id="footer_node">
<p class="a">I am in the footer node.</p>
</div>
</body>
</html>
use of getElementsByClass
is as simple as:
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");
$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".
I want to truncate a text or line with ellipsis using JavaScript
This will limit it to however many lines you want it limited to and is responsive
An idea that nobody has suggested, doing it based on the height of the element and then stripping it back from there.
Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 version
But basically you want to grab the line height of the element, loop through all the text and stop when its at a certain lines height:
'use strict';
var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;
var getLineHeight = function getLineHeight(element) {
var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
if (lineHeight === 'normal') {
// sucky chrome
return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
} else {
return parseFloat(lineHeight);
}
};
linesElement.addEventListener('change', function () {
truncateElement.innerHTML = truncateText;
var truncateTextParts = truncateText.split(' ');
var lineHeight = getLineHeight(truncateElement);
var lines = parseInt(linesElement.value);
while (lines * lineHeight < truncateElement.clientHeight) {
console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
truncateTextParts.pop();
truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
}
});
CSS
#truncateme {
width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}
How to replace a whole line with sed?
You can also use sed's change line to accomplish this:
sed -i "/aaa=/c\aaa=xxx" your_file_here
This will go through and find any lines that pass the aaa=
test, which means that the line contains the letters aaa=
. Then it replaces the entire line with aaa=xxx. You can add a ^
at the beginning of the test to make sure you only get the lines that start with aaa=
but that's up to you.
How to set Apache Spark Executor memory
create a file called spark-env.sh in spark/conf directory and
add this line
SPARK_EXECUTOR_MEMORY=2000m #memory size which you want to allocate for the executor
How to extract multiple JSON objects from one file?
Update: I wrote a solution that doesn't require reading the entire file in one go. It's too big for a stackoverflow answer, but can be found here jsonstream
.
You can use json.JSONDecoder.raw_decode
to decode arbitarily big strings of "stacked" JSON (so long as they can fit in memory). raw_decode
stops once it has a valid object and returns the last position where wasn't part of the parsed object. It's not documented, but you can pass this position back to raw_decode
and it start parsing again from that position. Unfortunately, the Python json
module doesn't accept strings that have prefixing whitespace. So we need to search to find the first none-whitespace part of your document.
from json import JSONDecoder, JSONDecodeError
import re
NOT_WHITESPACE = re.compile(r'[^\s]')
def decode_stacked(document, pos=0, decoder=JSONDecoder()):
while True:
match = NOT_WHITESPACE.search(document, pos)
if not match:
return
pos = match.start()
try:
obj, pos = decoder.raw_decode(document, pos)
except JSONDecodeError:
# do something sensible if there's some error
raise
yield obj
s = """
{"a": 1}
[
1
,
2
]
"""
for obj in decode_stacked(s):
print(obj)
prints:
{'a': 1}
[1, 2]
Command line input in Python
Start your script with the following line. The script will first run and then you will get the python command prompt. At this point all variables and functions will be available for interactive use and invocations.
#!/usr/bin/env python -i
Installing OpenCV 2.4.3 in Visual C++ 2010 Express
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to
repeat adding the OpenCV directories and in Additional
Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
- Go to the samples dir →
c:\opencv\samples\cpp
.
- Read and compile some code.
- Write your own code.
How to align flexbox columns left and right?
I came up with 4 methods to achieve the results. Here is demo
Method 1:
#a {
margin-right: auto;
}
Method 2:
#a {
flex-grow: 1;
}
Method 3:
#b {
margin-left: auto;
}
Method 4:
#container {
justify-content: space-between;
}
How to implement my very own URI scheme on Android
As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.
Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here
Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant.
Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html
Unable to locate an executable at "/usr/bin/java/bin/java" (-1)
For me, the problem occurs when I've downloaded macOS Compressed Archive
which underlying directory contains
jdk-11.0.8.jdk
- Contents
- Home
- bin
- ...
- MacOS
- _CodeSignature
So, to solve the problem, JAVA_HOME should be pointed directly to /Path-to-JDK/Contents/Home.
Scikit-learn train_test_split with indices
The docs mention train_test_split is just a convenience function on top of shuffle split.
I just rearranged some of their code to make my own example. Note the actual solution is the middle block of code. The rest is imports, and setup for a runnable example.
from sklearn.model_selection import ShuffleSplit
from sklearn.utils import safe_indexing, indexable
from itertools import chain
import numpy as np
X = np.reshape(np.random.randn(20),(10,2)) # 10 training examples
y = np.random.randint(2, size=10) # 10 labels
seed = 1
cv = ShuffleSplit(random_state=seed, test_size=0.25)
arrays = indexable(X, y)
train, test = next(cv.split(X=X))
iterator = list(chain.from_iterable((
safe_indexing(a, train),
safe_indexing(a, test),
train,
test
) for a in arrays)
)
X_train, X_test, train_is, test_is, y_train, y_test, _, _ = iterator
print(X)
print(train_is)
print(X_train)
Now I have the actual indexes: train_is, test_is
Java default constructor
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
Most efficient way to map function over numpy array
squares = squarer(x)
Arithmetic operations on arrays are automatically applied elementwise, with efficient C-level loops that avoid all the interpreter overhead that would apply to a Python-level loop or comprehension.
Most of the functions you'd want to apply to a NumPy array elementwise will just work, though some may need changes. For example, if
doesn't work elementwise. You'd want to convert those to use constructs like numpy.where
:
def using_if(x):
if x < 5:
return x
else:
return x**2
becomes
def using_where(x):
return numpy.where(x < 5, x, x**2)
Convert XML to JSON (and back) using Javascript
I was using xmlToJson just to get a single value of the xml.
I found doing the following is much easier (if the xml only occurs once..)
_x000D_
_x000D_
let xml =_x000D_
'<person>' +_x000D_
' <id>762384324</id>' +_x000D_
' <firstname>Hank</firstname> ' +_x000D_
' <lastname>Stone</lastname>' +_x000D_
'</person>';_x000D_
_x000D_
let getXmlValue = function(str, key) {_x000D_
return str.substring(_x000D_
str.lastIndexOf('<' + key + '>') + ('<' + key + '>').length,_x000D_
str.lastIndexOf('</' + key + '>')_x000D_
);_x000D_
}_x000D_
_x000D_
_x000D_
alert(getXmlValue(xml, 'firstname')); // gives back Hank
_x000D_
_x000D_
_x000D_
How to replace a string in a SQL Server Table Column
all answers are great but I just want to give you a good example
select replace('this value from table', 'table', 'table but updated')
this SQL statement will replace the existence of the word "table"
(second parameter) inside the given statement(first parameter) with the third parameter
the initial value is this value from table
but after executing replace function it will be this value from table but updated
and here is a real example
UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'
for example if we have this value
10.7440/perifrasis.2010.1.issue-1
it will become
10.25025/perifrasis.2010.1.issue-1
hope this gives you better visualization
Hibernate Criteria for Dates
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();
Get PostGIS version
Other way to get the minor version is:
SELECT extversion
FROM pg_catalog.pg_extension
WHERE extname='postgis'
How do I remove a library from the arduino environment?
Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.
Your Arduino library folder should look like this (on Windows):
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
My Documents\Arduino\libraries\ArduinoParty\examples
....
or like this (on Mac and Linux):
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
Documents/Arduino/libraries/ArduinoParty/examples
The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.
What is useState() in React?
The answers provided above are good but let me just chip in, useState
is async so if your next state is dependent on your previous state it is best you pass useState
a callback. See the example below:
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
// passing a callback to useState to update count
<button onClick={() => setCount(count => count + 1)}>
Click me
</button>
</div>
);
}
This is the recommended way if your new state depends on computation from the old state.
How to convert a JSON string to a Map<String, String> with Jackson JSON
Here is the generic solution to this problem.
public static <K extends Object, V extends Object> Map<K, V> getJsonAsMap(String json, K key, V value) {
try {
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<K, V>> typeRef = new TypeReference<Map<K, V>>() {
};
return mapper.readValue(json, typeRef);
} catch (Exception e) {
throw new RuntimeException("Couldnt parse json:" + json, e);
}
}
Hope someday somebody would think to create a util method to convert to any Key/value type of Map hence this answer :)
IF Statement multiple conditions, same statement
I think agileguy has the correct answer, but I would like to add that for more difficult situations there are a couple of strategies I take to solve the problem. The first is to use a truth table. If you Google "truth table" you will run across some examples related directly to programming and computer science.
Another strategy I take is to use an anonymous function to encapsulate common logic between various conditions. Create it right before the if block, then use it where needed. This seems to create code that is more readable and maintainable.
What is a JavaBean exactly?
As per the Wikipedia:
The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.
The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
The class should be serializable. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.)
For more information follow this link.
Character reading from file in Python
Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.
You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.
>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"
Alternatively you can use the iconv
command line utility to clean up your file:
$ xxd foo
0000000: e280 980a ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a '.
How to test if a double is an integer
Personally, I prefer the simple modulo operation solution in the accepted answer.
Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:
if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
// no decimal places
} else {
// decimal places
}
Remainder(BigDecimal)
returns a BigDecimal
whose value is (this % divisor)
. If this one's equal to zero, we know there is no floating point.
JavaScript CSS how to add and remove multiple CSS classes to an element
Maybe this will help you learn:
_x000D_
_x000D_
//<![CDATA[_x000D_
/* external.js */_x000D_
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere_x000D_
addEventListener('load', function(){_x000D_
doc = document; bod = doc.body; htm = doc.documentElement;_x000D_
C = function(tag){_x000D_
return doc.createElement(tag);_x000D_
}_x000D_
E = function(id){_x000D_
return doc.getElementById(id);_x000D_
}_x000D_
addClassName = function(element, className){_x000D_
var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');_x000D_
if(!element.className.match(rx)){_x000D_
element.className += ' '+className;_x000D_
}_x000D_
return element.className;_x000D_
}_x000D_
removeClassName = function(element, className){_x000D_
element.className = element.className.replace(new RegExp('\s?'+className), '');_x000D_
return element.className;_x000D_
}_x000D_
var out = E('output'), mn = doc.getElementsByClassName('main')[0];_x000D_
out.innerHTML = addClassName(mn, 'wow');_x000D_
out.innerHTML = addClassName(mn, 'cool');_x000D_
out.innerHTML = addClassName(mn, 'it works');_x000D_
out.innerHTML = removeClassName(mn, 'wow');_x000D_
out.innerHTML = removeClassName(mn, 'main');_x000D_
_x000D_
}); // close load_x000D_
//]]>
_x000D_
/* external.css */_x000D_
html,body{_x000D_
padding:0; margin:0;_x000D_
}_x000D_
.main{_x000D_
width:980px; margin:0 auto;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>_x000D_
<head>_x000D_
<meta http-equiv='content-type' content='text/html;charset=utf-8' />_x000D_
<link type='text/css' rel='stylesheet' href='external.css' />_x000D_
<script type='text/javascript' src='external.js'></script>_x000D_
</head>_x000D_
<body>_x000D_
<div class='main'>_x000D_
<div id='output'></div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
how to make a jquery "$.post" request synchronous
From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
Here's what your code would look like if changed as suggested:
beforecreate: function(node,targetNode,type,to) {
jQuery.ajax({
url: url,
success: function(result) {
if(result.isOk == false)
alert(result.message);
},
async: false
});
}
this is because $.ajax is the only request type that you can set the asynchronousity for
How to convert an integer to a string in any base?
Here is a recursive version that handles signed integers and custom digits.
import string
def base_convert(x, base, digits=None):
"""Convert integer `x` from base 10 to base `base` using `digits` characters as digits.
If `digits` is omitted, it will use decimal digits + lowercase letters + uppercase letters.
"""
digits = digits or (string.digits + string.ascii_letters)
assert 2 <= base <= len(digits), "Unsupported base: {}".format(base)
if x == 0:
return digits[0]
sign = '-' if x < 0 else ''
x = abs(x)
first_digits = base_convert(x // base, base, digits).lstrip(digits[0])
return sign + first_digits + digits[x % base]
How to correctly set Http Request Header in Angular 2
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });
How to deploy ASP.NET webservice to IIS 7?
- rebuild project in VS
- copy project folder to iis folder, probably C:\inetpub\wwwroot\
- in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
- add web service to created website, almost the same as 3.
- INSTALL ASP
for windows 7 and .net 4.0:
c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
- check access to web service on your browser
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How to use SSH to run a local shell script on a remote machine?
First, copy the script over to Machine B using scp
[user@machineA]$ scp /path/to/script user@machineB:/home/user/path
Then, just run the script
[user@machineA]$ ssh user@machineB "/home/user/path/script"
This will work if you have given executable permission to the script.
Flexbox and Internet Explorer 11 (display:flex in <html>?)
Use another flex container to fix the min-height
issue in IE10 and IE11:
HTML
<div class="ie-fixMinHeight">
<div id="page">
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
</div>
CSS
.ie-fixMinHeight {
display:flex;
}
#page {
min-height:100vh;
width:100%;
display:flex;
flex-direction:column;
}
#content {
flex-grow:1;
}
See a working demo.
- Don't use flexbox layout directly on
body
because it
screws up elements inserted via jQuery plugins (autocomplete, popup,
etc.).
- Don't use
height:100%
or height:100vh
on your container because the footer will stick at the bottom of window and won't adapt to long content.
- Use
flex-grow:1
rather than flex:1
cause IE10 and IE11 default values for flex
are 0 0 auto
and not 0 1 auto
.
How to check if a String is numeric in Java
Java 8 Stream, lambda expression, functional interface
All cases handled (string null, string empty etc)
String someString = null; // something="", something="123abc", something="123123"
boolean isNumeric = Stream.of(someString)
.filter(s -> s != null && !s.isEmpty())
.filter(Pattern.compile("\\D").asPredicate().negate())
.mapToLong(Long::valueOf)
.boxed()
.findAny()
.isPresent();
How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
Converting a vector<int> to string
Maybe std::ostream_iterator
and std::ostringstream
:
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(4);
vec.push_back(7);
vec.push_back(4);
vec.push_back(9);
vec.push_back(7);
std::ostringstream oss;
if (!vec.empty())
{
// Convert all but the last element to avoid a trailing ","
std::copy(vec.begin(), vec.end()-1,
std::ostream_iterator<int>(oss, ","));
// Now add the last element with no delimiter
oss << vec.back();
}
std::cout << oss.str() << std::endl;
}
Regular Expression to match every new line character (\n) inside a <content> tag
Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:
<!-- <content> blah </content> -->
You can take two approaches here:
- Strip all comments out first. Then use the regex approach.
- Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.
Be careful.
I am also not so sure you can match all new lines at once. @Quartz suggested this one:
<content>([^\n]*\n+)+</content>
This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:
<content>.*</content>
BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.
I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.
I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...
UPDATE 1:
Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):
To strip out comments, use this regex:
Notice the "?" suppresses the .* to make it non-greedy.
Similarly, to search for content tags, use:
.*?
Also, You may be able to try this out, and access each newline character with the match objects groups():
<content>(.*?(\n))+.*?</content>
I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.
UPDATE 2:
So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:
#!/usr/bin/python
import re
def FindContentNewlines(xml_text):
# May want to compile these regexes elsewhere, but I do it here for brevity
comments = re.compile(r"<!--.*?-->", re.DOTALL)
content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)
# strip comments: this actually may not be reliable for "nested comments"
# How does xml handle <!-- <!-- --> -->. I am not sure. But that COULD
# be trouble.
xml_text = re.sub(comments, "", xml_text)
result = []
all_contents = re.findall(content, xml_text)
for c in all_contents:
result.extend(re.findall(newlines, c))
return result
if __name__ == "__main__":
example = """
<!-- This stuff
ought to be omitted
<content>
omitted
</content>
-->
This stuff is good
<content>
<p>
haha!
</p>
</content>
This is not found
"""
print FindContentNewlines(example)
This program prints the result:
['', '<p>', ' haha!', '</p>', '']
The first and last empty strings come from the newline chars immediately preceeding the first <p>
and the one coming right after the </p>
. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.
Hope this helps :-).
PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.
Injection of autowired dependencies failed;
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources
From official documentation
Warning: Do not filter files with binary content like images! This
will most likely result in corrupt output.
If you have both text files and binary files as resources it is
recommended to have two separated folders. One folder
src/main/resources (default) for the resources which are not filtered
and another folder src/main/resources-filtered for the resources which
are filtered.
<project>
...
<build>
...
<resources>
<resource>
<directory>src/main/resources-filtered</directory>
<filtering>true</filtering>
</resource>
...
</resources>
...
</build>
...
</project>
Now you can put those files into src/main/resources which should not
filtered and the other files into src/main/resources-filtered.
As already mentioned filtering binary files like images,pdf`s etc.
could result in corrupted output. To prevent such problems you can
configure file extensions which will not being filtered.
Most certainly, You have in your directory files that cannot be filtered. So you have to specify the extensions that has not be filtered.
How can I sort one set of data to match another set of data in Excel?
You can use VLOOKUP
.
Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:
=VLOOKUP(A2, Sheet2!A:B, 2, 0)
This will return you #N/A
if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.
Numpy: find index of the elements within range
Summary of the answers
For understanding what is the best answer we can do some timing using the different solution.
Unfortunately, the question was not well-posed so there are answers to different questions, here I try to point the answer to the same question. Given the array:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
The answer should be the indexes of the elements between a certain range, we assume inclusive, in this case, 6 and 10.
answer = (3, 4, 5)
Corresponding to the values 6,9,10.
To test the best answer we can use this code.
import timeit
setup = """
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
# we define the left and right limit
ll = 6
rl = 10
def sorted_slice(a,l,r):
start = np.searchsorted(a, l, 'left')
end = np.searchsorted(a, r, 'right')
return np.arange(start,end)
"""
functions = ['sorted_slice(a,ll,rl)', # works only for sorted values
'np.where(np.logical_and(a>=ll, a<=rl))[0]',
'np.where((a >= ll) & (a <=rl))[0]',
'np.where((a>=ll)*(a<=rl))[0]',
'np.where(np.vectorize(lambda x: ll <= x <= rl)(a))[0]',
'np.argwhere((a>=ll) & (a<=rl)).T[0]', # we traspose for getting a single row
'np.where(ne.evaluate("(ll <= a) & (a <= rl)"))[0]',]
functions2 = [
'a[np.logical_and(a>=ll, a<=rl)]',
'a[(a>=ll) & (a<=rl)]',
'a[(a>=ll)*(a<=rl)]',
'a[np.vectorize(lambda x: ll <= x <= rl)(a)]',
'a[ne.evaluate("(ll <= a) & (a <= rl)")]',
]
Results
The results are reported in the following plot. On the top the fastest solutions.
If instead of the indexes you want to extract the values you can perform the tests using functions2 but the results are almost the same.
What does "Changes not staged for commit" mean
Try following int git bash
1.git add -u :/
2.git commit -m "your commit message"
git push -u origin master
Note:if you have not initialized your repo.
First of all
git init
and follow above mentioned steps in order.
This worked for me
How to check Elasticsearch cluster health?
PROBLEM :-
Sometimes, Localhost may not get resolved.
So it tends to return an output as seen below :
# curl -XGET localhost:9200/_cluster/health?pretty
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
# curl -XGET localhost:9200/_cat/indices
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
SOLUTION :-
Guess, this error is most probably returned by Local Squid deployed in the server.
So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.
return value after a promise
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
.mp4 file not playing in chrome
After running into the same issue - here're some of my thoughts:
- due to Chrome removing support for h264, on some machines, mp4 videos
encoded with it will either not work (throwing an Parser error when
viewing under Firebug/Network tab - consistent with issue submitted
here), or crash the browser, depending upon the encoding settings
- it isn't consistent - it entirely depends upon the codecs installed
on the computer - while I didn't encounter this issue on my machine,
we did have one in the office where the issue occurred (and thus we
used this one for testing)
- it might to do with Quicktime / divX settings (the machine in
question had an older version of Quicktime than my native one - we
didn't want to loose our testing pc though, so we didn't update it).
As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:
for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4)
apply following js:
if (window.chrome)
$("[type=video\\\/mp4]").each(function()
{
$(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
});
Unfortunately it's a bad Chrome hack, but hey, at least it works.
Source: user: eithedog
This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec
Also check your version of crome here: html5test
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
This answer covers a lot of ground, so it’s divided into three parts:
- How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems
- How to avoid the CORS preflight
- How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems
How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems
If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary Access-Control-Allow-Origin
header, you can still get things to work—by making the request through a CORS proxy.
You can easily run your own proxy using code from https://github.com/Rob--W/cors-anywhere/.
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., https://cryptic-headland-94862.herokuapp.com/
.
Now, prefix your request URL with the URL for your proxy:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:
- Forwards the request to
https://example.com
.
- Receives the response from
https://example.com
.
- Adds the
Access-Control-Allow-Origin
header to the response.
- Passes that response, with that added header, back to the requesting frontend code.
The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin
response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS
request, because in that case, the proxy also sends back the Access-Control-Allow-Headers
and Access-Control-Allow-Methods
headers needed to make the preflight successful.
How to avoid the CORS preflight
The code in the question triggers a CORS preflight—since it sends an Authorization
header.
https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
Even without that, the Content-Type: application/json
header would also trigger a preflight.
What “preflight” means: before the browser tries the POST
in the code in the question, it’ll first send an OPTIONS
request to the server — to determine if the server is opting-in to receiving a cross-origin POST
that has Authorization
and Content-Type: application/json
headers.
It works pretty well with a small curl script - I get my data.
To properly test with curl
, you must emulate the preflight OPTIONS
request the browser sends:
curl -i -X OPTIONS -H "Origin: http://127.0.0.1:3000" \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: Content-Type, Authorization' \
"https://the.sign_in.url"
…with https://the.sign_in.url
replaced by whatever your actual sign_in
URL is.
The response the browser needs to see from that OPTIONS
request must have headers like this:
Access-Control-Allow-Origin: http://127.0.0.1:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization
If the OPTIONS
response doesn’t include those headers, then the browser will stop right there and never even attempt to send the POST
request. Also, the HTTP status code for the response must be a 2xx—typically 200 or 204. If it’s any other status code, the browser will stop right there.
The server in the question is responding to the OPTIONS
request with a 501 status code, which apparently means it’s trying to indicate it doesn’t implement support for OPTIONS
requests. Other servers typically respond with a 405 “Method not allowed” status code in this case.
So you’re never going to be able to make POST
requests directly to that server from your frontend JavaScript code if the server responds to that OPTIONS
request with a 405 or 501 or anything other than a 200 or 204 or if doesn’t respond with those necessary response headers.
The way to avoid triggering a preflight for the case in the question would be:
- if the server didn’t require an
Authorization
request header but instead, e.g., relied on authentication data embedded in the body of the POST
request or as a query param
- if the server didn’t require the
POST
body to have a Content-Type: application/json
media type but instead accepted the POST
body as application/x-www-form-urlencoded
with a parameter named json
(or whatever) whose value is the JSON data
How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems
I am getting another error message:
The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is
'include'. Origin 'http://127.0.0.1:3000' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
For a request that includes credentials, browsers won’t let your frontend JavaScript code access the response if the value of the Access-Control-Allow-Origin
response header is *
. Instead the value in that case must exactly match your frontend code’s origin, http://127.0.0.1:3000
.
See Credentialed requests and wildcards in the MDN HTTP access control (CORS) article.
If you control the server you’re sending the request to, then a common way to deal with this case is to configure the server to take the value of the Origin
request header, and echo/reflect that back into the value of the Access-Control-Allow-Origin
response header; e.g., with nginx:
add_header Access-Control-Allow-Origin $http_origin
But that’s just an example; other (web) server systems provide similar ways to echo origin values.
I am using Chrome. I also tried using that Chrome CORS Plugin
That Chrome CORS plugin apparently just simplemindedly injects an Access-Control-Allow-Origin: *
header into the response the browser sees. If the plugin were smarter, what it would be doing is setting the value of that fake Access-Control-Allow-Origin
response header to the actual origin of your frontend JavaScript code, http://127.0.0.1:3000
.
So avoid using that plugin, even for testing. It’s just a distraction. To test what responses you get from the server with no browser filtering them, you’re better off using curl -H
as above.
As far as the frontend JavaScript code for the fetch(…)
request in the question:
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
Remove those lines. The Access-Control-Allow-*
headers are response headers. You never want to send them in a request. The only effect that’ll have is to trigger a browser to do a preflight.
How to install SQL Server Management Studio 2012 (SSMS) Express?
Good evening,
The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out.
When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2.
Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.
Cheers.
How to set a value for a selectize.js input?
Note setValue only works if there are already predefined set of values for the selectize control ( ex. select field ), for controls where the value could be dynamic ( ex. user can add values on the fly, textbox field ) setValue ain't gonna work.
Use createItem functon instead for adding and setting the current value of the selectize field
ex.
$selectize[ 0 ].selectize.clear(); // Clear existing entries
for ( var i = 0 ; i < data_source.length ; i++ ) // data_source is a dynamic source of data
$selectize[ 0 ].selectize.createItem( data_source[ i ] , false ); // false means don't trigger dropdown
What is the difference between XML and XSD?
XSD:
XSD (XML Schema Definition) specifies how to formally describe the elements in an Extensible Markup Language (XML) document.
Xml:
XML was designed to describe data.It is independent from software as well as hardware.
It enhances the following things.
-Data sharing.
-Platform independent.
-Increasing the availability of Data.
Differences:
XSD is based and written on XML.
XSD defines elements and structures that can appear in the document, while XML does not.
XSD ensures that the data is properly interpreted, while XML does not.
An XSD document is validated as XML, but the opposite may not always be true.
XSD is better at catching errors than XML.
An XSD defines elements that can be used in the documents, relating to the actual data with which it is to be encoded.
for eg:
A date that is expressed as 1/12/2010 can either mean January 12 or December 1st. Declaring a date data type in an XSD document, ensures that it follows the format dictated by XSD.
PHP date() format when inserting into datetime in MySQL
There is no need no use the date() method from PHP if you don't use a timestamp. If dateposted
is a datetime column, you can insert the current date like this:
$db->query("INSERT INTO table (dateposted) VALUES (now())");
How to rotate a div using jQuery
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
Pass multiple complex objects to a post/put Web API method
I know this is an old question, but I had the same issue and here is what I came up with and hopefully will be useful to someone. This will allow passing JSON formatted parameters individually in request URL (GET), as one single JSON object after ? (GET) or within single JSON body object (POST). My goal was RPC-style functionality.
Created a custom attribute and parameter binding, inheriting from HttpParameterBinding:
public class JSONParamBindingAttribute : Attribute
{
}
public class JSONParamBinding : HttpParameterBinding
{
private static JsonSerializer _serializer = JsonSerializer.Create(new JsonSerializerSettings()
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
public JSONParamBinding(HttpParameterDescriptor descriptor)
: base(descriptor)
{
}
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
HttpActionContext actionContext,
CancellationToken cancellationToken)
{
JObject jobj = GetJSONParameters(actionContext.Request);
object value = null;
JToken jTokenVal = null;
if (!jobj.TryGetValue(Descriptor.ParameterName, out jTokenVal))
{
if (Descriptor.IsOptional)
value = Descriptor.DefaultValue;
else
throw new MissingFieldException("Missing parameter : " + Descriptor.ParameterName);
}
else
{
try
{
value = jTokenVal.ToObject(Descriptor.ParameterType, _serializer);
}
catch (Newtonsoft.Json.JsonException e)
{
throw new HttpParseException(String.Join("", "Unable to parse parameter: ", Descriptor.ParameterName, ". Type: ", Descriptor.ParameterType.ToString()));
}
}
// Set the binding result here
SetValue(actionContext, value);
// now, we can return a completed task with no result
TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
tcs.SetResult(default(AsyncVoid));
return tcs.Task;
}
public static HttpParameterBinding HookupParameterBinding(HttpParameterDescriptor descriptor)
{
if (descriptor.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<JSONParamBindingAttribute>().Count == 0
&& descriptor.ActionDescriptor.GetCustomAttributes<JSONParamBindingAttribute>().Count == 0)
return null;
var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods;
if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Get))
{
return new JSONParamBinding(descriptor);
}
return null;
}
private JObject GetJSONParameters(HttpRequestMessage request)
{
JObject jobj = null;
object result = null;
if (!request.Properties.TryGetValue("ParamsJSObject", out result))
{
if (request.Method == HttpMethod.Post)
{
jobj = JObject.Parse(request.Content.ReadAsStringAsync().Result);
}
else if (request.RequestUri.Query.StartsWith("?%7B"))
{
jobj = JObject.Parse(HttpUtility.UrlDecode(request.RequestUri.Query).TrimStart('?'));
}
else
{
jobj = new JObject();
foreach (var kvp in request.GetQueryNameValuePairs())
{
jobj.Add(kvp.Key, JToken.Parse(kvp.Value));
}
}
request.Properties.Add("ParamsJSObject", jobj);
}
else
{
jobj = (JObject)result;
}
return jobj;
}
private struct AsyncVoid
{
}
}
Inject binding rule inside WebApiConfig.cs's Register method:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.ParameterBindingRules.Insert(0, JSONParamBinding.HookupParameterBinding);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
This allows for controller actions with default parameter values and mixed complexity, as such:
[JSONParamBinding]
[HttpPost, HttpGet]
public Widget DoWidgetStuff(Widget widget, int stockCount, string comment="no comment")
{
... do stuff, return Widget object
}
example post body:
{
"widget": {
"a": 1,
"b": "string",
"c": { "other": "things" }
},
"stockCount": 42,
"comment": "sample code"
}
or GET single param (needs URL encoding)
controllerPath/DoWidgetStuff?{"widget":{..},"comment":"test","stockCount":42}
or GET multiple param (needs URL encoding)
controllerPath/DoWidgetStuff?widget={..}&comment="test"&stockCount=42
How to select id with max date group by category in PostgreSQL?
This is a perfect use-case for DISTINCT ON
- a Postgres specific extension of the standard DISTINCT
:
SELECT DISTINCT ON (category)
id -- , category, date -- any other column (expression) from the same row
FROM tbl
ORDER BY category, date DESC;
Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST
:
DISTINCT ON
is simple and fast. Detailed explanation in this related answer:
For big tables with many rows per category
consider an alternative approach:
ToList().ForEach in Linq
Try this:
foreach (var dept in employees.SelectMany(e => e.Departments))
{
dept.SomeProperty = null;
collection.Add(dept);
}
jQuery Loop through each div
$('div.target').each(function() {
/* Measure the width of each image. */
var test = $(this).find('.scrolling img').width();
/* Find out how many images there are. */
var testimg = $(this).find('.scrolling img').length;
/* Do the maths. */
var final = (test* testimg)*1.2;
/* Apply the maths to the CSS. */
$(this).find('scrolling').width(final);
});
Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this)
to indicate the currently selected <div>
tag.
Class Not Found: Empty Test Suite in IntelliJ
For me the project was compiled outside the project. I just change the path.
For changing the path (i'm using mac).
- Go to File --> Project Structure
- Go to Module on left side.
- Select Paths, select radio button(use module compile output path)
- Provide output path and Test output path which is inside your project
- Deselect Exclude output paths.
- Go to File --> Click on Invalidate Cache and restart
What is the equivalent of Java static methods in Kotlin?
except Michael Anderson's answer, i have coding with other two way in my project.
First:
you can white all variable to one class.
created a kotlin file named Const
object Const {
const val FIRST_NAME_1 = "just"
const val LAST_NAME_1 = "YuMu"
}
You can use it in kotlin and java code
Log.d("stackoverflow", Const.FIRST_NAME_1)
Second:
You can use Kotlin's extension function
created a kotlin file named Ext, below code is the all code in Ext file
package pro.just.yumu
/**
* Created by lpf on 2020-03-18.
*/
const val FIRST_NAME = "just"
const val LAST_NAME = "YuMu"
You can use it in kotlin code
Log.d("stackoverflow", FIRST_NAME)
You can use it in java code
Log.d("stackoverflow", ExtKt.FIRST_NAME);
How to programmatically connect a client to a WCF service?
You'll have to use the ChannelFactory class.
Here's an example:
var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
IMyService client = null;
try
{
client = myChannelFactory.CreateChannel();
client.MyServiceOperation();
((ICommunicationObject)client).Close();
myChannelFactory.Close();
}
catch
{
(client as ICommunicationObject)?.Abort();
}
}
Related resources:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1
The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.
How to detect if CMD is running as Administrator/has elevated privileges?
Here's a slight modification of Harry's answer that focuses on elevated status; I'm using this at the start of an install.bat file:
set IS_ELEVATED=0
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1
if %IS_ELEVATED%==0 (
echo You must run the command prompt as administrator to install.
exit /b 1
)
This definitely worked for me and the principle seems to be sound; from MSFT's Chris Jackson:
When you are running elevated, your token contains an ACE called Mandatory Label\High Mandatory Level.
DB query builder toArray() laravel 4
You can do this using the query builder. Just use SELECT instead of TABLE and GET.
DB::select('select * from user where name = ?',['Jhon']);
Notes:
1. Multiple question marks are allowed.
2. The second parameter must be an array, even if there is only one parameter.
3. Laravel will automatically clean parameters, so you don't have to.
Further info here: http://laravel.com/docs/5.0/database#running-queries
Hmmmmmm, turns out that still returns a standard class for me when I don't use a where clause. I found this helped:
foreach($results as $result)
{
print_r(get_object_vars($result));
}
However, get_object_vars isn't recursive, so don't use it on $results.
When should an Excel VBA variable be killed or set to Nothing?
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
Filter object properties by key in ES6
If you have a list of allowed values, you can easily retain them in an object using:
_x000D_
_x000D_
const raw = {_x000D_
item1: { key: 'sdfd', value:'sdfd' },_x000D_
item2: { key: 'sdfd', value:'sdfd' },_x000D_
item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3'];_x000D_
_x000D_
const filtered = Object.keys(raw)_x000D_
.filter(key => allowed.includes(key))_x000D_
.reduce((obj, key) => {_x000D_
obj[key] = raw[key];_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_
This uses:
Object.keys
to list all properties in raw
(the original data), then
Array.prototype.filter
to select keys that are present in the allowed list, using
Array.prototype.includes
to make sure they are present
Array.prototype.reduce
to build a new object with only the allowed properties.
This will make a shallow copy with the allowed properties (but won't copy the properties themselves).
You can also use the object spread operator to create a series of objects without mutating them (thanks to rjerue for mentioning this):
_x000D_
_x000D_
const raw = {_x000D_
item1: { key: 'sdfd', value:'sdfd' },_x000D_
item2: { key: 'sdfd', value:'sdfd' },_x000D_
item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3'];_x000D_
_x000D_
const filtered = Object.keys(raw)_x000D_
.filter(key => allowed.includes(key))_x000D_
.reduce((obj, key) => {_x000D_
return {_x000D_
...obj,_x000D_
[key]: raw[key]_x000D_
};_x000D_
}, {});_x000D_
_x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_
For purposes of trivia, if you wanted to remove the unwanted fields from the original data (which I would not recommend doing, since it involves some ugly mutations), you could invert the includes
check like so:
_x000D_
_x000D_
const raw = {_x000D_
item1: { key: 'sdfd', value:'sdfd' },_x000D_
item2: { key: 'sdfd', value:'sdfd' },_x000D_
item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3'];_x000D_
_x000D_
Object.keys(raw)_x000D_
.filter(key => !allowed.includes(key))_x000D_
.forEach(key => delete raw[key]);_x000D_
_x000D_
console.log(raw);
_x000D_
_x000D_
_x000D_
I'm including this example to show a mutation-based solution, but I don't suggest using it.
Search and get a line in Python
items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
you can also get the line if there are other characters before token
items=re.findall("^.*token.*$",s,re.MULTILINE)
The above works like grep token on unix and keyword 'in' or .contains in python and C#
s='''
qwertyuiop
asdfghjkl
zxcvbnm
token qwerty
asdfghjklñ
'''
http://pythex.org/
matches the following 2 lines
....
....
token qwerty
Calculating Page Table Size
Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...*
now we know that no. of pages in page table is
pages=total possible logical address entries/page size
so pages=2^32/2^12 =2^20
Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***
How to get a reference to an iframe's window object inside iframe's onload handler created from parent window
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
What I can do to resolve "1 commit behind master"?
If your branch is behind by master then do:
git checkout master (you are switching your branch to master)
git pull
git checkout yourBranch (switch back to your branch)
git merge master
After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:
git push
If there is a conflict then fix your file(s), then:
git add yourFile(s)
git commit -m 'updating my branch'
git push
Creating a thumbnail from an uploaded image
UPDATE:
If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile
because I was having issues with it on my server. File put contents works just as well.
<?php
/**
*
* Generate Thumbnail using Imagick class
*
* @param string $img
* @param string $width
* @param string $height
* @param int $quality
* @return boolean on true
* @throws Exception
* @throws ImagickException
*/
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = reset(explode('.', $img));
if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}
// example usage
try {
generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == IMAGETYPE_GIF) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == IMAGETYPE_JPEG) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == IMAGETYPE_PNG) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.
Gradle does not find tools.jar
I got the same error using Eclipse trying to execute a Gradle Task. Every time I run a command (i.e. war) the process threw an exception like:
Could not find tools.jar. Please check that C:\Program Files\Java\Jre8" is a valid JDK install.
I tried the solution listed in this post but none of them solved this issue. Here my solution :
- Go to the "Gradle Task" view
- Right Click on the task you want to execute
- Select Open Gradle Run Configuration
- In the tab "Java Home" select your local JDK repository then click OK
Run again, Enjoy!
Reportviewer tool missing in visual studio 2017 RC
Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:
If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:
- Microsoft.DataTools.ReportingServices.vsix, and
- Microsoft.RdlcDesigner.vsix
Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:
- Microsoft.ReportViewer.Common.dll
- Microsoft.ReportViewer.DataVisualization.dll
- Microsoft.ReportViewer.Design.dll
- Microsoft.ReportViewer.ProcessingObjectModel.dll
- Microsoft.ReportViewer.WinForms.dll
Install the 2 components from 1 above
- Add the dlls from 2 above as references (Project>References>Add...)
- (Optional) Add Reporting tab to the toolbar
- Add Items to Reporting tab
- Browse to the bin folder or where you have the above dlls and add them
You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project
NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!
Create SQL script that create database and tables
In SQL Server Management Studio you can right click on the database you want to replicate, and select "Script Database as" to have the tool create the appropriate SQL file to replicate that database on another server. You can repeat this process for each table you want to create, and then merge the files into a single SQL file. Don't forget to add a using statement after you create your Database but prior to any table creation.
In more recent versions of SQL Server you can get this in one file in SSMS.
- Right click a database.
- Tasks
- Generate Scripts
This will launch a wizard where you can script the entire database or just portions. There does not appear to be a T-SQL way of doing this.
Exception: "URI formats are not supported"
string ImagePath = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
string a = "";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
if (receiveStream.CanRead)
{ a = "OK"; }
}
catch { }
Returning Promises from Vuex actions
TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.
For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.
But, there are EDGE CASES where returning a promise from your actions might be "necessary".
Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently.
In that case, one would need to pass the caller component as a parameter to set different flags in the store.
Dumb example
Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous.
If the promise fails, the page should only display an error in the component the user was trying to change the username from.
Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.
Why are C++ inline functions in the header?
I know this is an old thread but thought I should mention that the extern
keyword. I've recently ran into this issue and solved as follows
Helper.h
namespace DX
{
extern inline void ThrowIfFailed(HRESULT hr);
}
Helper.cpp
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
std::stringstream ss;
ss << "#" << hr;
throw std::exception(ss.str().c_str());
}
}
}
Escape double quotes in a string
In C#, there are at least 4 ways to embed a quote within a string:
- Escape quote with a backslash
- Precede string with @ and use double quotes
- Use the corresponding ASCII character
- Use the Hexadecimal Unicode character
Please refer this document for detailed explanation.
Insert data using Entity Framework model
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
Replacing Spaces with Underscores
As of others have explained how to do it using str_replace
, you can also use regex to achieve this.
$name = preg_replace('/\s+/', '_', $name);
Returning Arrays in Java
As Luiggi mentioned you need to change your main to:
import java.util.Arrays;
public class trial1{
public static void main(String[] args){
int[] A = numbers();
System.out.println(Arrays.toString(A)); //Might require import of util.Arrays
}
public static int[] numbers(){
int[] A = {1,2,3};
return A;
}
}
How can I find the number of elements in an array?
It is not possible to find the number of elements in an array unless it is a character array. Consider the below example:
int main()
{
int arr[100]={1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
printf("%d", size);
return 1;
}
The above value gives us value 100 even if the number of elements is five.
If it is a character array, you can search linearly for the null string at the end of the array and increase the counter as you go through.
&& (AND) and || (OR) in IF statements
Java has 5 different boolean compare operators: &, &&, |, ||, ^
& and && are "and" operators, | and || "or" operators, ^ is "xor"
The single ones will check every parameter, regardless of the values, before checking the values of the parameters.
The double ones will first check the left parameter and its value and if true
(||
) or false
(&&
) leave the second one untouched.
Sound compilcated? An easy example should make it clear:
Given for all examples:
String aString = null;
AND:
if (aString != null & aString.equals("lala"))
Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.
if (aString != null && aString.equals("lala"))
The first parameter is checked and it returns false
, so the second paramter won't be checked, because the result is false
anyway.
The same for OR:
if (aString == null | !aString.equals("lala"))
Will raise NullPointerException, too.
if (aString == null || !aString.equals("lala"))
The first parameter is checked and it returns true
, so the second paramter won't be checked, because the result is true
anyway.
XOR can't be optimized, because it depends on both parameters.