I was in your shoes for a while and finally ended up using node.js, because it can do hybrid solutions like having web and socket server in one. So php backend can submit requests thru http to node web server and then broadcast it with websocket. Very efficiant way to go.
var str='1232323a.1';
var reg=/^[0-9]*[.]?[0-9]*$/;
console.log(reg.test(str))
_x000D_
You can factor out your common logic to a private method, for example called Initialize
that gets called from both constructors.
Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.
Example:
public Point2D(double x, double y)
{
// Contracts
Initialize(x, y);
}
public Point2D(Point2D point)
{
if (point == null)
throw new ArgumentNullException("point");
// Contracts
Initialize(point.X, point.Y);
}
private void Initialize(double x, double y)
{
X = x;
Y = y;
}
According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):
The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance:
31 * i == (i << 5) - i
. Modern VMs do this sort of optimization automatically.
(from Chapter 3, Item 9: Always override hashcode when you override equals, page 48)
git clone -b 13.1rc1-Gotham --depth 1 https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Counting objects: 17977, done.
remote: Compressing objects: 100% (13473/13473), done.
Receiving objects: 36% (6554/17977), 19.21 MiB | 469 KiB/s
Will be faster than :
git clone https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects: 14% (40643/282238), 55.46 MiB | 578 KiB/s
Or
git clone -b 13.1rc1-Gotham https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects: 12% (34441/282238), 20.25 MiB | 461 KiB/s
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
In View:
@ViewBag.Name
@ViewData["Name"]
@tokland
tried your code and corrected it for 3.4 and windows dir.cmd is a simple dir command, saved as cmd-file
import subprocess
c = "dir.cmd"
def execute(command):
popen = subprocess.Popen(command, stdout=subprocess.PIPE,bufsize=1)
lines_iterator = iter(popen.stdout.readline, b"")
while popen.poll() is None:
for line in lines_iterator:
nline = line.rstrip()
print(nline.decode("latin"), end = "\r\n",flush =True) # yield line
execute(c)
Use git-gui (or similar) to perform a git commit --amend
. From the GUI you can add or remove individual files from the commit. You can also modify the commit message.
Just reset your branch to the previous location (for example, using gitk
or git rebase
). Then reapply your changes from a saved copy. After garbage collection in your local repository, it will be like the unwanted commit never happened. To do all of that in a single command, use git reset HEAD~1
.
Word of warning: Careless use of git reset
is a good way to get your working copy into a confusing state. I recommend that Git novices avoid this if they can.
Perform a reverse cherry pick (git-revert) to undo the changes.
If you haven't yet pulled other changes onto your branch, you can simply do...
git revert --no-edit HEAD
Then push your updated branch to the shared repository.
The commit history will show both commits, separately.
Also note: You don't want to do this if someone else may be working on the branch.
git push --delete (branch_name) ## remove public version of branch
Clean up your branch locally then repush...
git push origin (branch_name)
In the normal case, you probably needn't worry about your private-branch commit history being pristine. Just push a followup commit (see 'How to undo a public commit' above), and later, do a squash-merge to hide the history.
Instead of configuring Tomcat to redirect requests, use Apache as a frontend with the Apache Tomcat connector so that Apache is only serving static content, while asking tomcat for dynamic content.
Using the JKmount directive (or others) you could specify exactly which requests are sent to Tomcat.
Requests for static content, such as images, would be served directly by Apache, using a standard virtual host configuration, while other requests, defined in the JKMount directive will be sent to Tomcat workers.
I think this implementation would give you the most flexibility and control on the overall application.
In Weblogic 9.2 the configuration via console is as follows:
I believe the default value was 60
.
Remember to use Release Configuration
button after you edit the field.
My understanding is that this is actually very simple:
So, to work through some of your examples:
function f(a,b,c) {
// Argument a is re-assigned to a new value.
// The object or primitive referenced by the original a is unchanged.
a = 3;
// Calling b.push changes its properties - it adds
// a new property b[b.length] with the value "foo".
// So the object referenced by b has been changed.
b.push("foo");
// The "first" property of argument c has been changed.
// So the object referenced by c has been changed (unless c is a primitive)
c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
Example 2:
var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4"; // a is now ["1", "4", {foo:"bar"}]; b still has the value
// it had at the time of assignment
a[2] = "5"; // a is now ["1", "4", "5"]; c still has the value
// it had at the time of assignment, i.e. a reference to
// the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked")
to get all checkboxes and radio buttons that are checked.
Ok i was previously not aware that AngularJS
usually refers to Angular
v1 version and only Angular to Angular v2+
This answer only applies for Angular
Leaving this here for future reference..
Not sure how it works for you guys but on Angular 9 i have to wrap ngStyle in brackets like this:
[ng-style]="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"
Otherwise it doesn't work
Most of the answers did not generalize enough and pandas reindex_axis method is a little tedious, hence I offer a simple function to move an arbitrary number of columns to any position using a dictionary where key = column name and value = position to move to. If your dataframe is large pass True to 'big_data' then the function will return the ordered columns list. And you could use this list to slice your data.
def order_column(df, columns, big_data = False):
"""Re-Orders dataFrame column(s)
Parameters :
df -- dataframe
columns -- a dictionary:
key = current column position/index or column name
value = position to move it to
big_data -- boolean
True = returns only the ordered columns as a list
the user user can then slice the data using this
ordered column
False = default - return a copy of the dataframe
"""
ordered_col = df.columns.tolist()
for key, value in columns.items():
ordered_col.remove(key)
ordered_col.insert(value, key)
if big_data:
return ordered_col
return df[ordered_col]
# e.g.
df = pd.DataFrame({'chicken wings': np.random.rand(10, 1).flatten(), 'taco': np.random.rand(10,1).flatten(),
'coffee': np.random.rand(10, 1).flatten()})
df['mean'] = df.mean(1)
df = order_column(df, {'mean': 0, 'coffee':1 })
>>>
col = order_column(df, {'mean': 0, 'coffee':1 }, True)
col
>>>
['mean', 'coffee', 'chicken wings', 'taco']
# you could grab it by doing this
df = df[col]
The Java XML parser that spring uses will read the schemaLocation
values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.
If you omit the schemaLocation
, then the XML parser won't know where to get the schema in order to validate the config.
Why myList[1] is considered a 'str' object?
Because it is a string. What else is 'from form'
, if not a string? (Actually, strings are sequences too, i.e. they can be indexed, sliced, iterated, etc. as well - but that's part of the str
class and doesn't make it a list or something).
mList[1]
returns the first item in the list'from form'
If you mean that myList
is 'from form'
, no it's not!!! The second (indexing starts at 0) element is 'from form'
. That's a BIG difference. It's the difference between a house and a person.
Also, myList
doesn't have to be a list
from your short code sample - it could be anything that accepts 1
as index - a dict with 1 as index, a list, a tuple, most other sequences, etc. But that's irrelevant.
but I cannot append to item 1 in the list
myList
Of course not, because it's a string and you can't append to string. String are immutable. You can concatenate (as in, "there's a new object that consists of these two") strings. But you cannot append
(as in, "this specific object now has this at the end") to them.
You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.
This is how I solved this issue:
One thing you can do is to use raw SQL:
case class Bar(x1: Int, y1: Int, z1: Int, v1: String)
case class Foo(x2: Int, y2: Int, z2: Int, v2: String)
val bar = sqlContext.createDataFrame(sc.parallelize(
Bar(1, 1, 2, "bar") :: Bar(2, 3, 2, "bar") ::
Bar(3, 1, 2, "bar") :: Nil))
val foo = sqlContext.createDataFrame(sc.parallelize(
Foo(1, 1, 2, "foo") :: Foo(2, 1, 2, "foo") ::
Foo(3, 1, 2, "foo") :: Foo(4, 4, 4, "foo") :: Nil))
foo.registerTempTable("foo")
bar.registerTempTable("bar")
sqlContext.sql(
"SELECT * FROM foo LEFT JOIN bar ON x1 = x2 AND y1 = y2 AND z1 = z2")
I constantly forget the names of the colors I want to use and keep coming back to this question =)
The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.
I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.
I really didn't change much from the matplotlib example, but here is the code for completeness.
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
n = len(sorted_names)
ncols = 4
nrows = n // ncols
fig, ax = plt.subplots(figsize=(12, 10))
# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols
for i, name in enumerate(sorted_names):
row = i % nrows
col = i // nrows
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y + h * 0.1, xi_line, xf_line,
color=colors[name], linewidth=(h * 0.8))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
Updated 2017-10-25. I merged my previous updates into this section.
If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:
plt.plot([1,2], lw=4, c='xkcd:baby poop green')
Now you have access to a plethora of named colors!
The default Tableau colors are available in matplotlib via the 'tab:' prefix:
plt.plot([1,2], lw=4, c='tab:green')
There are ten distinct colors:
You can also plot colors by their HTML hex code:
plt.plot([1,2], lw=4, c='#8f9805')
This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...
For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py
.
adb shell
am start -n com.package.name/com.package.name.ActivityName
Or you can use this directly:
adb shell am start -n com.package.name/com.package.name.ActivityName
You can also specify actions to be filter by your intent-filters:
am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName
For adding borders try this, for example:
Range("C11").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("A15:D15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Hope that syntax is correct because I've done this in C#.
I assume from db
that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type of thing you can do:
select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };
You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
Are you sure it is smaller?
Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
Log.e("Original dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());
Gives
12-07 17:43:36.333: E/Original dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768
Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density
Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());
12-07 17:43:38.733: E/Dimensions(278): 768 576
For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.
For that need to add the 2021 partition into that table
ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS
use JodaTime
The ISO 8601 calendar system is the default implementation within Joda-Time
Here is the doc for JodaTime Formatter
Edit:
If you don't want to add or if you don't see value of adding above library you could just use in built SimpleDateFormat
class to format the Date to required ISO format
as suggested by @Joachim Sauer
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());
You may also have a look at some NIO application framework such as:
The strdup() function is a shorthand for string duplicate, it takes in a parameter as a string constant or a string literal and allocates just enough space for the string and writes the corresponding characters in the space allocated and finally returns the address of the allocated space to the calling routine.
I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta
table. You can find the corresponding products within wp_posts
table.
The absolute simplest way to accomplish this, is with basename()
echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');
Which will print
9393903
Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.
An API incompatibility I found, with Python 2.7 vs simplejson 3.3.1 is in whether output produces str or unicode objects. e.g.
>>> from json import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode("""{ "a":"b" }""")
{u'a': u'b'}
vs
>>> from simplejson import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode("""{ "a":"b" }""")
{'a': 'b'}
If the preference is to use simplejson, then this can be addressed by coercing the argument string to unicode, as in:
>>> from simplejson import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode(unicode("""{ "a":"b" }""", "utf-8"))
{u'a': u'b'}
The coercion does require knowing the original charset, for example:
>>> jd.decode(unicode("""{ "a": "?????ßß?f?e?" }"""))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 8: ordinal not in range(128)
This is the won't fix issue 40
This is not really a shortcut but just a quick access to the control menu: Alt-space E P
If you can use your mouse, right click on the cmd window works as paste when I tried it.
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
Take a look at this article; under the heading "Methods provided at runtime":
Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.
...
Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."
The @synthesize
directive, on the other hand, generates the accessor methods for you at compile time (although as noted in the "Mixing Synthesized and Custom Accessors" section it is flexible and does not generate methods for you if either are implemented).
For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170
I'm not sure if I understand your question, but I'll take a stab at it:
td {
border: 1px solid #000;
}
tr td:last-child {
width: 1%;
white-space: nowrap;
}
_x000D_
<table style="width: 100%;">
<tr>
<td class="block">this should stretch</td>
<td class="block">this should stretch</td>
<td class="block">this should be the content width</td>
</tr>
</table>
_x000D_
You could always write out the list of keys in addition to dumping the dict, and then reconstruct the OrderedDict
by iterating through the list?
Just add this and all works well:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
just added this to my class
@XmlAccessorType(XmlAccessType.FIELD)
worked like a cham
A common idiom to change every element of a list looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
See enumerate.
put x=0 outside the for loop that is the problem
If you are using JetBrains Idea IDE (and derivatives) you can select several lines, right click for the context menu, then Git -> Show history for selection. You will see list of commits which were affecting the selected lines:
To substantiate @deceze's claim that the default JSON encoding is UTF-8...
From IETF RFC4627:
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.
00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8
Try this:
int lowIndex = 0;
int highIndex = elements.length-1;
while(lowIndex < highIndex) {
T lowVal = elements[lowIndex];
T highVal = elements[highIndex];
elements[lowIndex] = highVal;
elements[highIndex] = lowVal;
lowIndex += 1;
highIndex -=1;
}
Finally I able resolve this issue.
Do not install Android SDK with studio package, unkcheck the option when asked.
Steps to resolve:
I tried other solutions, run as Administrator and proxy setting but nothing worked.
function substrCount( str, x ) {
let count = -1, pos = 0;
do {
pos = str.indexOf( x, pos ) + 1;
count++;
} while( pos > 0 );
return count;
}
If you are trying to open a file in the same directory it would be:
./PROGRAM TRYING TO OPEN
./FILE NAME/PROGRAM TRYING TO OPEN (or this)
Or, if trying to backtrack from the same directory it would be:
../PROGRAM TRYING TO OPEN
../FILE NAME/PROGRAM TRYING TO OPEN (or this)
Else, if you need a straight one from start, it would be:
(DIRECTORY TYPE)\Users\%username%\(FILE DIRECTORY)
(ex) C:\Users\ajste\Desktop\Henlo.cmd
If I have the class:
public class MyClass
{
public void MyMethod()
{
}
}
and I then do:
MyClass myClass = null;
myClass.MyMethod();
The second line throws this exception becuase I'm calling a method on a reference type object that is null
(I.e. has not been instantiated by calling myClass = new MyClass()
)
ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:
function IsFileSizeOk(fileid) {
try {
var fileSize = 0;
//for IE
if (navigator.userAgent.match(/msie/i)) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
return (fileSize < 2.0);
}
catch (e) {
alert("Error is :" + e);
}
}
If you have only two or three condition(sizes)
then you can use @Overide onMeasure
like
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
And change your size for these conditions in CustomView class easily.
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
Django Mail Templated is a feature-rich Django application to send emails with Django template system.
Installation:
pip install django-mail-templated
Configuration:
INSTALLED_APPS = (
...
'mail_templated'
)
Template:
{% block subject %}
Hello {{ user.name }}
{% endblock %}
{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}
Python:
from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])
More info: https://github.com/artemrizhov/django-mail-templated
const arr = JSON.parse(json);
obj.id = obj._id;
delete obj._id;
All together:
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
const json = `
[
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 2"
}
]
`;
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
console.log( updatedJson );
_x000D_
Quick way to print something is:
select '** Place your mesage here' AS '** DEBUG:';
The solutions so far cover some cases but miss some (see below). Here's my attempt at a more thorough (safe) conversion. I know of one corner case which this solution doesn't handle which is single character symbols made up of odd, but allowed characters. For example {:> => :<}
is a valid ruby hash.
I put this code up on github as well. This code starts with a test string to exercise all the conversions
require 'json'
# Example ruby hash string which exercises all of the permutations of position and type
# See http://json.org/
ruby_hash_text='{"alpha"=>{"first second > third"=>"first second > third", "after comma > foo"=>:symbolvalue, "another after comma > foo"=>10}, "bravo"=>{:symbol=>:symbolvalue, :aftercomma=>10, :anotheraftercomma=>"first second > third"}, "charlie"=>{1=>10, 2=>"first second > third", 3=>:symbolvalue}, "delta"=>["first second > third", "after comma > foo"], "echo"=>[:symbol, :aftercomma], "foxtrot"=>[1, 2]}'
puts ruby_hash_text
# Transform object string symbols to quoted strings
ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')
# Transform object string numbers to quoted strings
ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')
# Transform object value symbols to quotes strings
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')
# Transform array value symbols to quotes strings
ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')
# Transform object string object value delimiter to colon delimiter
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')
puts ruby_hash_text
puts JSON.parse(ruby_hash_text)
Here are some notes on the other solutions here
eval
which is too scary for me (as Toms rightly points out).Just Use this method and pass your lat, long.
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
//Set Address
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
A good rule of thumb: use the built-in help system in Python. Example below...
jdoe@server:~$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)
------------------------------------------
NAME
memcache - client module for memcached (memory cache daemon)
FILE
/usr/lib/python2.7/dist-packages/memcache.py
MODULE DOCS
http://docs.python.org/library/memcache
DESCRIPTION
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
...
------------------------------------------
I guess the uname answer is unbeatable, mainly in terms of cleanliness.
Although it takes a ridiculous time to execute, I found that testing for specific files presence also gives me good and quicker results, since I'm not invoking an executable:
So,
[ -f /usr/bin/cygwin1.dll ] && echo Yep, Cygwin running
just uses a quick Bash file presence check. As I'm on Windows right now, I can't tell you any specific files for Linuxes and Mac OS X from my head, but I'm pretty sure they do exist. :-)
Since @MaciejTreder confirmed that we have to loop, here's a wrapper that will optionally let you add to a set of default params:
function genParams(params: object, httpParams = new HttpParams()): object {
Object.keys(params)
.filter(key => {
let v = params[key];
return (Array.isArray(v) || typeof v === 'string') ?
(v.length > 0) :
(v !== null && v !== undefined);
})
.forEach(key => {
httpParams = httpParams.set(key, params[key]);
});
return { params: httpParams };
}
You can use it like so:
const OPTIONS = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
params: new HttpParams().set('verbose', 'true')
};
let opts = Object.assign({}, OPTIONS, genParams({ id: 1 }, OPTIONS.params));
this.http.get(BASE_URL, opts); // --> ...?verbose=true&id=1
One more note, for our web application, I found that we had huge performance issues due to contention between threads over locks... so the moral was to think over the locking scheme very carefully. We ended up having worker threads to throttle too many requests using an asynchronous http handler, otherwise the application would just get overwhelmed and crash and burn. It meant a huge backlog could pile up, but at least the site would stay up.
Select the range of cells, type in the value and press Ctrl + Enter.
This, of course, is true if you want to do it manually.
For me this error happened because I was trying to call a nested function. Only thing I had to do to have it fixed was to bring the function out to a scope where it was visible.
I prefer to use ***_join
in dplyr
whenever I need to match data. One possible try for this
left_join(data.frame(name=target),df,by="name")
Note that the input for ***_join
require tbls or data.frame
pymongo
Finding objects between two dates in Python with pymongo
in collection posts
(based on the tutorial):
from_date = datetime.datetime(2010, 12, 31, 12, 30, 30, 125000)
to_date = datetime.datetime(2011, 12, 31, 12, 30, 30, 125000)
for post in posts.find({"date": {"$gte": from_date, "$lt": to_date}}):
print(post)
Where {"$gte": from_date, "$lt": to_date}
specifies the range in terms of datetime.datetime
types.
First, don't do it that way. The best approach is to use find -exec
properly:
# this is safe
find test -type d -exec echo '{}' +
The other safe approach is to use NUL-terminated list, though this requires that your find support -print0
:
# this is safe
while IFS= read -r -d '' n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d -print0)
You can also populate an array from find, and pass that array later:
# this is safe
declare -a myarray
while IFS= read -r -d '' n; do
myarray+=( "$n" )
done < <(find test -mindepth 1 -type d -print0)
printf '%q\n' "${myarray[@]}" # printf is an example; use it however you want
If your find doesn't support -print0
, your result is then unsafe -- the below will not behave as desired if files exist containing newlines in their names (which, yes, is legal):
# this is unsafe
while IFS= read -r n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d)
If one isn't going to use one of the above, a third approach (less efficient in terms of both time and memory usage, as it reads the entire output of the subprocess before doing word-splitting) is to use an IFS
variable which doesn't contain the space character. Turn off globbing (set -f
) to prevent strings containing glob characters such as []
, *
or ?
from being expanded:
# this is unsafe (but less unsafe than it would be without the following precautions)
(
IFS=$'\n' # split only on newlines
set -f # disable globbing
for n in $(find test -mindepth 1 -type d); do
printf '%q\n' "$n"
done
)
Finally, for the command-line parameter case, you should be using arrays if your shell supports them (i.e. it's ksh, bash or zsh):
# this is safe
for d in "$@"; do
printf '%s\n' "$d"
done
will maintain separation. Note that the quoting (and the use of $@
rather than $*
) is important. Arrays can be populated in other ways as well, such as glob expressions:
# this is safe
entries=( test/* )
for d in "${entries[@]}"; do
printf '%s\n' "$d"
done
onkeydown
is fired when the key is down (like in shortcuts; for example, in Ctrl+A
, Ctrl
is held 'down'.
onkeyup
is fired when the key is released (including modifier/etc keys)
onkeypress
is fired as a combination of onkeydown
and onkeyup
, or depending on keyboard repeat (when onkeyup
isn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!)
textInput
(webkit only) is fired when some text is entered (for example, Shift+A
would enter uppercase 'A', but Ctrl+A
would select text and not enter any text input. In that case, all other events are fired)
Note also, each command's exit status is stored in the shell variable $?, which you can check immediately after running the command. A non-zero status indicates failure:
my_command
if [ $? -eq 0 ]
then
echo "it worked"
else
echo "it failed"
fi
Unless you're really worried about older browsers, you could just use the new html5 placeholder
attribute like so:
<input type="text" name="email" placeholder="Email address" class="input" />
Yet another way to use Rscript for *Unix systems is Process Substitution.
Rscript <(zcat a.r)
# [1] "hello"
Which obviously does the same as the accepted answer, but this allows you to manipulate and run your file without saving it the power of the command line, e.g.:
Rscript <(sed s/hello/bye/ a.r)
# [1] "bye"
Similar to Rscript -e "Rcode"
it also allows to run without saving into a file. So it could be used in conjunction with scripts that generate R-code, e.g.:
Rscript <(echo "head(iris,2)")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
I tried all solutions above (Native, changing url of VCS repository, updating Git, updating IDEA, invalidating Caches), but nothing helped me. Finally I found solution that works for me.
SOLUTION: I closed Idea and replaced content of file ~\.IntelliJIdea20xx.x\config\options\git.xml
with this:
<application>
<component name="Git.Application.Settings">
<option name="SSH_EXECUTABLE" value="IDEA_SSH" />
</component>
</application>
Then I started IDEA, try to checkout SSH GIT repository and it works and existing projects works as well. Interesting fact is that when I switch to NATIVE in Idea Settings, repository not working.
I slightly modified the printer example to make it more explainable
1 document which had 2 pages content was sent to printer
Transaction - document sent to printer
Hope this helps someone to get the hang of the concept of ACID
Callback for whenever a TR element is created for the table's body.
$('#example').dataTable( {
"createdRow": function( row, data, dataIndex ) {
if ( data[4] == "A" ) {
$(row).addClass( 'important' );
}
}
} );
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)
def cmd_std_output(cd_dir_path, cmd):
cmd_to_list = cmd.split(" ")
try:
if cd_dir_path:
os.chdir(os.path.abspath(cd_dir_path))
output = check_output(cmd_to_list, stderr=STDOUT).decode()
return output
except CalledProcessError as e:
log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
cd_dir_path = "/repos/cc_manager/cc_cluster"
cmd = "git log --name-status HEAD^..HEAD --date=iso"
result = cmd_std_output(cd_dir_path, cmd)
return result
log.debug("Output: {}".format(get_last_commit_cc_cluster()))
Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e\nAuthor: user1<[email protected]>\nDate: 2020-04-23 09:58:49 +0200\n\n
Notice the repetition of Book
in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)
- it screams for a class type.
class Book {
int number;
String title;
String language;
int price;
}
Now you can simply have:
Book[] books = new Books[3];
If you want arrays, you can declare it as object array an insert Integer
and String
into it:
Object books[3][4]
In this scenario, the outer <div>
has a width and height of 90%. The inner div>
has a width of 100% of its parent. Both scale when re-sizing the window.
HTML
<div>
<div>Hello there</div>
</div>
CSS
html, body {
width: 100%;
height: 100%;
}
body > div {
width: 90%;
height: 100%;
background: green;
}
body > div > div {
width: 100%;
background: red;
}
Demo
Here's a more general technique for left-padding to any desired width:
declare @x int = 123 -- value to be padded
declare @width int = 25 -- desired width
declare @pad char(1) = '0' -- pad character
select right_justified = replicate(
@pad ,
@width-len(convert(varchar(100),@x))
)
+ convert(varchar(100),@x)
However, if you're dealing with negative values, and padding with leading zeroes, neither this, nor other suggested technique will work. You'll get something that looks like this:
00-123
[Probably not what you wanted]
So … you'll have to jump through some additional hoops Here's one approach that will properly format negative numbers:
declare @x float = -1.234
declare @width int = 20
declare @pad char(1) = '0'
select right_justified = stuff(
convert(varchar(99),@x) , -- source string (converted from numeric value)
case when @x < 0 then 2 else 1 end , -- insert position
0 , -- count of characters to remove from source string
replicate(@pad,@width-len(convert(varchar(99),@x)) ) -- text to be inserted
)
One should note that the convert()
calls should specify an [n]varchar
of sufficient length to hold the converted result with truncation.
There are several ways in which you can set the timeout for php-fpm. In /etc/php5/fpm/pool.d/www.conf
I added this line:
request_terminate_timeout = 180
Also, in /etc/nginx/sites-available/default
I added the following line to the location block of the server in question:
fastcgi_read_timeout 180;
The entire location block looks like this:
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_read_timeout 180;
include fastcgi_params;
}
Now just restart php-fpm and nginx and there should be no more timeouts for requests taking less than 180 seconds.
This is a one line to solve the complete original question:
params.select { |k,_| k[/choice/]}.values.join('\t')
But most the solutions above are solving a case where you need to know the keys ahead of time, using slice
or simple regexp.
Here is another approach that works for simple and more complex use cases, that is swappable at runtime
data = {}
matcher = ->(key,value) { COMPLEX LOGIC HERE }
data.select(&matcher)
Now not only this allows for more complex logic on matching the keys or the values, but it is also easier to test, and you can swap the matching logic at runtime.
Ex to solve the original issue:
def some_method(hash, matcher)
hash.select(&matcher).values.join('\t')
end
params = { :irrelevant => "A String",
:choice1 => "Oh look, another one",
:choice2 => "Even more strings",
:choice3 => "But wait",
:irrelevant2 => "The last string" }
some_method(params, ->(k,_) { k[/choice/]}) # => "Oh look, another one\\tEven more strings\\tBut wait"
some_method(params, ->(_,v) { v[/string/]}) # => "Even more strings\\tThe last string"
In Tomcat 7 (under Windows server) I didn't add or edit anything to any configuration file. I just renamed the ROOT folder to something else and renamed my application folder to ROOT and it worked fine.
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
This is the code part from this page:
CREATE FUNCTION [fn_ParseText2Table]
(@p_SourceText VARCHAR(MAX)
,@p_Delimeter VARCHAR(100)=',' --default to comma delimited.
)
RETURNS @retTable
TABLE([Position] INT IDENTITY(1,1)
,[Int_Value] INT
,[Num_Value] NUMERIC(18,3)
,[Txt_Value] VARCHAR(MAX)
,[Date_value] DATETIME
)
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
& return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (<A href="mailto:[email protected]">[email protected]</A>)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
Reworked to allow for delimiters > 1 character in length
and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/
BEGIN
DECLARE @w_xml xml;
SET @w_xml = N'<root><i>' + replace(@p_SourceText, @p_Delimeter,'</i><i>') + '</i></root>';
INSERT INTO @retTable
([Int_Value]
, [Num_Value]
, [Txt_Value]
, [Date_value]
)
SELECT CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
END AS [Int_Value]
, CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
END AS [Num_Value]
, [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
, CASE
WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
END AS [Num_Value]
FROM @w_xml.nodes('//root/i') AS [Items]([i]);
RETURN;
END;
GO
If you need an easier way to do it, and don't want much fuss, a simple execution could be:
raise Exception.new('something bad happened!')
This will raise an exception, say e
with e.message = something bad happened!
and then you can rescue it as you are rescuing all other exceptions in general.
Not orthodox, but it works for me sometimes; set your comment as another attribute:
<node usefulAttr="foo" comment="Your comment here..."/>
Nice find with your PureText. I had build, before I change keyboard, a key that was running a macro that was copying-pasting-copying in notepad for this task! I'll give a try to your software since I do not have any macro key now :(
It should be considered an error. But C is an ancient language, so it's only a warning.
Compiling with -Werror
(gcc) fixes this problem.
When C doesn't find a declaration, it assumes this implicit declaration: int f();
, which means the function can receive whatever you give it, and returns an integer. If this happens to be close enough (and in case of printf
, it is), then things can work. In some cases (e.g. the function actually returns a pointer, and pointers are larger than ints), it may cause real trouble.
Note that this was fixed in newer C standards (C99, C11). In these standards, this is an error. However, gcc
doesn't implement these standards by default, so you still get the warning.
I'm assuming c++ here. If you're using c#, the answer is probably the same, but the syntax will be a bit different. The enum is a set of int values. It's not an object, so you shouldn't be setting it to null. Setting something to null means you are pointing a pointer to an object to address zero. You can't really do that with an int. What you want to do with an int is to set it to a value you wouldn't normally have it at so that you can tel if it's a good value or not. So, set your colour to -1
Color color = -1;
Or, you can start your enum at 1 and set it to zero. If you set the colour to zero as it is right now, you will be setting it to "red" because red is zero in your enum.
So,
enum Color {
red =1
blue,
green
}
//red is 1, blue is 2, green is 3
Color mycolour = 0;
I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file
tr:nth-of-type(odd)
{
background-color: red;
}
tr:nth-of-type(even)
{
background-color: blue;
}
The bootstrap table-striped class will over ride your selectors.
If you are using FirebaseUI, no need of FirebaseApp.initializeApp(this);
in your code according the sample.
Make sure to add to your root-level build.gradle :
buildscript {
repositories {
google()
jcenter()
}
dependencies {
...
classpath 'com.google.gms:google-services:3.1.1'
...
}
}
Then, in your module level Gradle file :
dependencies {
...
// 1 - Required to init Firebase automatically (THE MAGIC LINE)
implementation "com.google.firebase:firebase-core:11.6.2"
// 2 - FirebaseUI for Firebase Auth (Or whatever you need...)
implementation 'com.firebaseui:firebase-ui-auth:3.1.2'
...
}
apply plugin: 'com.google.gms.google-services'
That's it. No need more.
Since "detached head state" has you on a temp branch, just use git checkout -
which puts you on the last branch you were on.
You can create a single script that calls all the others.
Put the following into a batch file:
@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"
When you run that batch file it will create a new script named all.sql
in the same directory where the batch file is located. It will look for all files with the extension .sql
in the same directory where the batch file is located.
You can then run all scripts by using sqlplus user/pwd @all.sql
(or extend the batch file to call sqlplus
after creating the all.sql
script)
To add the Tomcat 9.0 (Tomcat build from the trunk) as a server in Eclipse.
Update the ServerInfo.properties file properties as below.
server.info=Apache Tomcat/@VERSION@
server.number=@VERSION_NUMBER@
server.built=@VERSION_BUILT@
server.info=Apache Tomcat/7.0.57
server.number=7.0.57.0
server.built=Nov 3 2014 08:39:16 UTC
Build the tomcat server from trunk and add the server as tomcat7 instance in Eclipse.
ServerInfo.properties file location : \tomcat\java\org\apache\catalina\util\ServerInfo.properties
UITableView
has a property separatorInset
. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.
[tableView setSeparatorInset:UIEdgeInsetsZero];
Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
$('body').bind('beforeunload',function(){
//do something
});
But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload
event does not always fire in all browsers.
Example: http://jsfiddle.net/maniator/qpK7Y/
Code:
$(window).bind('beforeunload',function(){
//save info somewhere
return 'are you sure you want to leave?';
});
If there are leading or trailing spaces, it'll be invalid. Trailing/Leading spaces can be removed as
mystring = mystring.replace(/^\s+|\s+$/g, "");
Source: http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html
I would try using netem on linux. With it you can simulate additional delay, corruption, packet loss and duplication. It even works on the loopback device.
If you have Gimp, I saw that exporting the image in .eps format would do the job.
Assuming you have Windows.Form Form1
as the parent form which owns the menu you've created. One of the form's attributes is named .Menu
. If the menu was created programmatically, it should be the same, and it would be recognized as a menu and placed in the Menu attribute of the Form.
In this case, I had a main menu called File
. A sub menu, called a MenuItem
under File
contained the tag Open
and was named menu_File_Open
. The following worked. Assuming you
// So you don't have to fully reference the objects.
using System.Windows.Forms;
// More stuff before the real code line, but irrelevant to this discussion.
MenuItem my_menuItem = (MenuItem)Form1.Menu.MenuItems["menu_File_Open"];
// Now you can do what you like with my_menuItem;
$ git branch --set-upstream-to=heroku/master master
and
$ git pull
worked for me!
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
None of these worked for me in SSIS v18.0, so I would up doing something like this:
WHERE CHARINDEX('_', thingyoursearching) < 1
..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:
WHERE CHARINDEX('_', thingyoursearching) > 0
I did not test the following snippet... hopefully it will point you towards the right direction:
var jsreader = new JsonTextReader(new StringReader(stringData));
var json = (JObject)new JsonSerializer().Deserialize(jsreader);
var tableRows = from p in json["items"]
select new
{
Name = (string)p["Name"],
Age = (int)p["Age"],
Job = (string)p["Job"]
};
To convert your object
in JSON with Jackson:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
If only the field is required
you could go with input:valid
#foo-thing:valid + .msg { visibility: visible!important; }
_x000D_
<input type="text" id="foo-thing" required="required">_x000D_
<span class="msg" style="visibility: hidden;">Yay not empty</span>
_x000D_
See live on jsFiddle
OR negate using #foo-thing:invalid
(credit to @SamGoody)
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
This will do it without painful manipulation or multiple command sequences:
build/%.o: src/%.cpp src/%.o: src/%.cpp %.o: $(CC) -c $< -o $@ build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o $(LD) $^ -o $@
JasperE has explained why "%.o: %.cpp" won't work; this version has one pattern rule (%.o:) with commands and no prereqs, and two pattern rules (build/%.o: and src/%.o:) with prereqs and no commands. (Note that I put in the src/%.o rule to deal with src/ui/flash.o, assuming that wasn't a typo for build/ui/flash.o, so if you don't need it you can leave it out.)
build/test.exe needs build/widgets/apple.o,
build/widgets/apple.o looks like build/%.o, so it needs src/%.cpp (in this case src/widgets/apple.cpp),
build/widgets/apple.o also looks like %.o, so it executes the CC command and uses the prereqs it just found (namely src/widgets/apple.cpp) to build the target (build/widgets/apple.o)
You can check the content's height by setting to 1px
and then reading the scrollHeight
property:
function textAreaAdjust(element) {
element.style.height = "1px";
element.style.height = (25+element.scrollHeight)+"px";
}
_x000D_
<textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>
_x000D_
It works under Firefox 3, IE 7, Safari, Opera and Chrome.
My recommendation is to use basename
.
It is by default in Ubuntu, visually simple code and deal with majority of cases.
Here are some sub-cases to deal with spaces and multi-dot/sub-extension:
pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}
It usually get rid of extension from first .
, but fail in our ..
path
echo **"$(basename "${pathfile%.*}")"**
space -file.tar # I believe we needed exatly that
Here is an important note:
I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.
However, you still need to think of .hidden_files
hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")" # will produce "~" !!!
not the expected "" outcome. To make it happen use $HOME
or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)
hidden2="$HOME/.bashrc" ; echo '$(basename "${pathfile%.*}")'
I ran into this problem today, and finding no good solutions for it, I created a module to address it. I was inspired by @fbartho's snippet, but wanted to avoid overwriting the fs module.
The module I wrote is Filequeue, and you use it just like fs:
var Filequeue = require('filequeue');
var fq = new Filequeue(200); // max number of files to open at once
fq.readdir('/Users/xaver/Downloads/xaver/xxx/xxx/', function(err, files) {
if(err) {
throw err;
}
files.forEach(function(file) {
fq.readFile('/Users/xaver/Downloads/xaver/xxx/xxx/' + file, function(err, data) {
// do something here
}
});
});
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
I tried lots of these suggestions, but the only thing that finally worked for me was creating a new workspace, and freshly checking out all my projects into that folder. Then it worked fine ;-)
This work for me with sample PDO :
public function GetTableColumn() {
$query = $this->db->prepare("SHOW COLUMNS FROM `what_table` LIKE 'what_column'");
try{
$query->execute();
if($query->fetchColumn()) { return 1; }else{ return 0; }
}catch(PDOException $e){die($e->getMessage());}
}
The easiest way to enumerate a dictionary is
for (NSString *key in tDictionary.keyEnumerator)
{
//do something here;
}
where tDictionary
is the NSDictionary
or NSMutableDictionary
you want to iterate.
DON'T be tempted to do things like this:
Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'
This is a better way:
Select * from [User] U
where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')
see: What does the word “SARGable” really mean?
EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).
2014-02-07
. It is far more efficient to alter the criteria to suit the data instead. "Amending the criteria to suit the data" is my way of describing "use SARGABLE
predicates"
And do not use between either.
the best practice with date and time ranges is to avoid BETWEEN and to always use the form:
WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable.
http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)
The only thing I can add to Stephan202's answer is a recommendation that you take a look at David Beazley's PyCon '08 presentation "Generator Tricks for Systems Programmers," which is the best single explanation of the how and why of generators that I've seen anywhere. This is the thing that took me from "Python looks kind of fun" to "This is what I've been looking for." It's at http://www.dabeaz.com/generators/.
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:
public class GenericListFilter<T> extends Filter {
/**
* Copycat constructor
* @param list the original list to be used
*/
public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
super ();
mInternalList = new ArrayList<>(list);
mAdapterUsed = adapter;
try {
ParameterizedType stringListType = (ParameterizedType)
getClass().getField("mInternalList").getGenericType();
mCompairMethod =
stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
}
catch (Exception ex) {
Log.w("GenericListFilter", ex.getMessage(), ex);
try {
if (mInternalList.size() > 0) {
T type = mInternalList.get(0);
mCompairMethod = type.getClass().getMethod(reflectMethodName);
}
}
catch (Exception e) {
Log.e("GenericListFilter", e.getMessage(), e);
}
}
}
/**
* Let's filter the data with the given constraint
* @param constraint
* @return
*/
@Override protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<T> filteredContents = new ArrayList<>();
if ( constraint.length() > 0 ) {
try {
for (T obj : mInternalList) {
String result = (String) mCompairMethod.invoke(obj);
if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
filteredContents.add(obj);
}
}
}
catch (Exception ex) {
Log.e("GenericListFilter", ex.getMessage(), ex);
}
}
else {
filteredContents.addAll(mInternalList);
}
results.values = filteredContents;
results.count = filteredContents.size();
return results;
}
/**
* Publish the filtering adapter list
* @param constraint
* @param results
*/
@Override protected void publishResults(CharSequence constraint, FilterResults results) {
mAdapterUsed.clear();
mAdapterUsed.addAll((List<T>) results.values);
if ( results.count == 0 ) {
mAdapterUsed.notifyDataSetInvalidated();
}
else {
mAdapterUsed.notifyDataSetChanged();
}
}
// class properties
private ArrayAdapter<T> mAdapterUsed;
private List<T> mInternalList;
private Method mCompairMethod;
}
And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:
this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);
The only thing missing now, is to override the "getFilter" method in the adapter class:
@Override public Filter getFilter () {
return MyViewClass.this.mFilter;
}
All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.
"npm start"
I just closed the terminal and open a new one. Went to project location by cd command. And then just simply type - "npm start". and then 'r' for reload. Everything just vanished. I think everybody should try this at once.
How would one specify multiple algorithms? I ask because git just updated on my work laptop, (Windows 10, using the official Git for Windows build,) and I got this error when I tried to push a project branch to my Azure DevOps remote. I tried to push --set-upstream and got this:
Unable to negotiate with 20.44.80.98 port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1,diffie-hellman-group14-sha1
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
So how would one implement the suggestions above allowing for both of those? (As a quick get-it-done, I used @golvok's solution with group14 and it worked, but I really don't know if 1 or 14 is better, etc.)
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
You have to figure out if the string is ascii encoded or encoded with a multi-byte format.
In the former case, you can just use strlen
.
In the latter case you need to find the number of bytes per character.
the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274
I had PHP7.2 on a Ubuntu 16.04 server and it solved my problem:
sudo apt-get install zip unzip php-zip
Update
Tried this for Ubuntu 18.04 and worked as well.
You can use span
elements instead of the br
if you want the white space method to work, as it depends on pseudo-elements which are "not defined" for replaced elements.
HTML
<p>
To break lines<span class="line-break">in a paragraph,</span><span>don't use</span><span>the 'br' element.</span>
</p>
CSS
span {white-space: pre;}
span:after {content: ' ';}
span.line-break {display: block;}
span.line-break:after {content: none;}
The line break is simply achieved by setting the appropriate span element to display:block
.
By using IDs and/ or Classes in your HTML markup you can easily target every single or combination of span elements by CSS or use CSS selectors like nth-child()
.
So you can e.g. define different break points by using media queries for a responsive layout.
And you can also simply add/ remove/ toggle classes by Javascript (jQuery).
The "advantage" of this method is its robustness - works in every browser that supports pseudo-elements (see: Can I use - CSS Generated content).
As an alternative it is also possible to add a line break via pseudo-elements:
span.break:before {
content: "\A";
white-space: pre;
}
The correct syntax for this is...
Session::set('variableName', $value);
For Laravel 5.4 and later, the correct method to use is put
.
Session::put('variableName', $value);
To get the variable, you'd use...
Session::get('variableName');
If you need to set it once, I'd figure out when exactly you want it set and use Events to do it. For example, if you want to set it when someone logs in, you'd use...
Event::listen('auth.login', function()
{
Session::set('variableName', $value);
});
If you want to be a little bit fancier you can also create it as an html list to create something like bullets or numbers using ul or ol.
<ul>
<li>Line 1</li>
<li>Line 2</li>
</ul>
If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...
Just add this somewhere in your code:
$(document).ready(
$('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
e.preventDefault();
}),
$('[data-toggle="collapse"]').on('click', function(e) {
e.preventDefault();
$($(this).data('target')).toggleClass('in');
})
);
Using fancybox version: 2.1.5 and tried all of the different options suggest here and none of them worked still showing the scrollbar.
$('.foo').click(function(e){
$.fancybox({
href: $(this).data('href'),
type: 'iframe',
scrolling: 'no',
iframe : {
scrolling : 'no'
}
});
e.preventDefault();
});
So did some debugging in the code until I found this, so its overwriting all options I set and no way to overwrite this using the many options.
if (type === 'iframe' && isTouch) {
coming.scrolling = 'scroll';
}
In the end the solutions was to use CSS !important hack.
.fancybox-inner {
overflow: hidden !important;
}
The line of code responsible is:
current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
Fancybox used to be a reliable working solution now I am finding nothing but inconsistencies. Actually debating about downgrading now even after purchasing a developers license. More info here if you didn't realize you needed one for commercial project: https://stackoverflow.com/a/8837258/560287
First things first :) reading books is an excellent approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might choose to interpret the 1
as a number, but environment variables don't care. They just pass around strings:
The argument envp is an array of character pointers to null-
terminated strings. These strings shall constitute the
environment for the new process image. The envp array is
terminated by a null pointer.
(From environ(3posix)
.)
You access environment variables in python using the os.environ
dictionary-like object:
>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'
I've converted the http://html5pattern.com/Dates Full Date Validation (YYYY-MM-DD) to DD/MM/YYYY Brazilian format:
pattern='(?:((?:0[1-9]|1[0-9]|2[0-9])\/(?:0[1-9]|1[0-2])|(?:30)\/(?!02)(?:0[1-9]|1[0-2])|31\/(?:0[13578]|1[02]))\/(?:19|20)[0-9]{2})'
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
Repeat:
UIImage *img = [UIImage imageNamed:@"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];
Stretched
UIImage *img = [UIImage imageNamed:@"bg.png"];
view.layer.contents = img.CGImage;
Use Below Code instead of your code
<EditText
android:id="@+id/searchbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:inputType="text"
android:scrollHorizontally="true"
android:ellipsize="end"
android:layout_weight="1"
android:layout_marginTop="2dp"
android:drawablePadding="10dp"
android:background="@drawable/edittext"
android:drawableLeft="@drawable/folder_full"
android:drawableRight="@drawable/search"
android:paddingLeft="15dp"
android:hint="search..."/>
Data List is a new HTML tag in HTML5 supported browsers. It renders as a text box with some list of options. For Example for Gender Text box it will give you options as Male Female when you type 'M' or 'F' in Text Box.
<input list="Gender">
<datalist id="Gender">
<option value="Male">
<option value="Female>
</datalist>
As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.
How to use after we created the ButtonEx-class:
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpfEx="clr-namespace:WpfExtensions"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
</Grid>
</Window>
ButtonEx.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfExtensions
{
/// <summary>
/// Standard button with extensions
/// </summary>
public partial class ButtonEx : Button
{
readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;
public ButtonEx()
{
InitializeComponent();
}
public Brush HoverBackground
{
get { return (Brush)GetValue(HoverBackgroundProperty); }
set { SetValue(HoverBackgroundProperty, value); }
}
public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
"HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
}
}
ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button
<Button x:Class="WpfExtensions.ButtonEx"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
x:Name="buttonExtension">
<Button.Resources>
<Style x:Key="FocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
</Button.Resources>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
<Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsDefaulted" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.
For jQuery 1.8+, this will no longer work because the internal data is placed in a different object.
The latest unofficial (but works in previous versions as well, at least in 1.7.2) way of doing it now is -
$._data(element, "events")
The underscore ("_") is what makes the difference here. Internally, it is calling $.data(element, name, null, true)
, the last (fourth) parameter is an internal one ("pvt").
There's more to it than this, but you're probably looking for this list:
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
H hourly frequency
T minutely frequency
S secondly frequency
L milliseconds
U microseconds
Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.
We can always use array of strings for multiline strings like following.
{
"singleLine": "Some singleline String",
"multiline": ["Line one", "line Two", "Line Three"]
}
And we can easily iterate array to display content in multi line fashion.
In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>(){}.getType());
}
sample call:
List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
Append code snippet to iterate over Map.entrySet()
:
${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
${keyType} ${key} = ${entry}.getKey();
${valueType} ${value} = ${entry}.getValue();
${cursor}
}
for (Entry<String, String> entry : properties.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
|
}
Or maybe you could use this script to install Go and LiteIDE?
If you are unhappy with the answer provided, please comment instead of blindly down voting. I have used this setup for the last 4 years without any issue.
If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal
package's terminal. See platformio-ide-terminal
provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:
$ apm install platformio-ide-terminal --no-confirm
Alternatively, you can install it from the command palette with:
platformio-ide-terminal
. Today I came across multiple solutions for this. Running the async await functions in the forEach Loop. By building the wrapper around we can make this happen.
The multiple ways through which it can be done and they are as follows,
Method 1 : Using the wrapper.
await (()=>{
return new Promise((resolve,reject)=>{
items.forEach(async (item,index)=>{
try{
await someAPICall();
} catch(e) {
console.log(e)
}
count++;
if(index === items.length-1){
resolve('Done')
}
});
});
})();
Method 2: Using the same as a generic function of Array.prototype
Array.prototype.forEachAsync.js
if(!Array.prototype.forEachAsync) {
Array.prototype.forEachAsync = function (fn){
return new Promise((resolve,reject)=>{
this.forEach(async(item,index,array)=>{
await fn(item,index,array);
if(index === array.length-1){
resolve('done');
}
})
});
};
}
Usage :
require('./Array.prototype.forEachAsync');
let count = 0;
let hello = async (items) => {
// Method 1 - Using the Array.prototype.forEach
await items.forEachAsync(async () => {
try{
await someAPICall();
} catch(e) {
console.log(e)
}
count++;
});
console.log("count = " + count);
}
someAPICall = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("done") // or reject('error')
}, 100);
})
}
hello(['', '', '', '']); // hello([]) empty array is also be handled by default
Method 3 :
Using Promise.all
await Promise.all(items.map(async (item) => {
await someAPICall();
count++;
}));
console.log("count = " + count);
Method 4 : Traditional for loop or modern for loop
// Method 4 - using for loop directly
// 1. Using the modern for(.. in..) loop
for(item in items){
await someAPICall();
count++;
}
//2. Using the traditional for loop
for(let i=0;i<items.length;i++){
await someAPICall();
count++;
}
console.log("count = " + count);
I guess it's a little too late now however the only time it does make a difference is when you set up HTML signatures on MS Outlook (even 2010). It's just not able to handle .html extensions, only .htm
Python suggests users use len()
instead of __len__()
for consistency, just like other guys said. However, There're some other benefits:
For some built-in types like list
, str
, bytearray
and so on, the Cython implementation of len()
takes a shortcut. It directly returns the ob_size
in a C structure, which is faster than calling __len__()
.
If you are interested in such details, you could read the book called "Fluent Python" by Luciano Ramalho. There're many interesting details in it, and may help you understand Python more deeply.
Modify to suit your specifics, or make more generic as needed:
Private Sub CopyItOver()
Set NewBook = Workbooks.Add
Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub
This is pretty easy using the JavaScript selenium-webdriver
client:
First, make sure you have a WebDriver server running. For example, download ChromeDriver, then run chromedriver --port=9515
.
Second, create the driver like this:
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.usingServer('http://localhost:9515') // <- this
.build();
Here's a complete example:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.usingServer('http://localhost:9515')
.build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.getTitle().then(function(title) {
console.log(title);
});
driver.quit();
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
Not all browsers support event capturing (for example, Internet Explorer versions less than 9 don't) but all do support event bubbling, which is why it is the phase used to bind handlers to events in all cross-browser abstractions, jQuery's included.
The nearest to what you are looking for in jQuery is using bind()
(superseded by on()
in jQuery 1.7+) or the event-specific jQuery methods (in this case, click()
, which calls bind()
internally anyway). All use the bubbling phase of a raised event.
You can't call a non-static method without first creating an instance of its parent class.
So from the static method, you would have to instantiate a new object...
Vehicle myCar = new Vehicle();
... and then call the non-static method.
myCar.Drive();
You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key.
DELETE FROM tableA
WHERE ROWID IN
( SELECT q.ROWID
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
Like Jon Skeet says, use the Process.Exited
:
proc.StartInfo.FileName = exportPath + @"\" + fileExe;
proc.Exited += new EventHandler(myProcess_Exited);
proc.Start();
inProcess = true;
while (inProcess)
{
proc.Refresh();
System.Threading.Thread.Sleep(10);
if (proc.HasExited)
{
inProcess = false;
}
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
inProcess = false;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\n", proc.ExitTime, proc.ExitCode);
}
^
is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow
.
You can do the same in python by simply importing the second file, code at the top level will run when imported. I'd suggest this is messy at best, and not a good programming practice. You would be better off organizing your code into modules
Example:
F1.py:
print "Hello, "
import f2
F2.py:
print "World!"
When run:
python ./f1.py
Hello,
World!
Edit to clarify: The part I was suggesting was "messy" is using the import
statement only for the side effect of generating output, not the creation of separate source files.
You can use LINQ:
using System.Linq;
IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList();
You need to follow the steps described in Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out and add your own Windows user as a member of sysadmin:
-m
and -f
startup parameters (or you can start sqlservr.exe -c -sEXPRESS -m -f
from console)sqlcmd -E -A -S .\EXPRESS
or from SSMS use admin:.\EXPRESS
create login [machinename\username] from windows
to create your Windows login in SQLsp_addsrvrolemember 'machinename\username', 'sysadmin';
to make urself sysadmin member-m -f
I always thought this was one of the better articles on the subject. It includes the following example that I think makes it clear and includes the frequently overlooked @@trancount which is needed for reliable nested transactions
PRINT 'BEFORE TRY'
BEGIN TRY
BEGIN TRAN
PRINT 'First Statement in the TRY block'
INSERT INTO dbo.Account(AccountId, Name , Balance) VALUES(1, 'Account1', 10000)
UPDATE dbo.Account SET Balance = Balance + CAST('TEN THOUSAND' AS MONEY) WHERE AccountId = 1
INSERT INTO dbo.Account(AccountId, Name , Balance) VALUES(2, 'Account2', 20000)
PRINT 'Last Statement in the TRY block'
COMMIT TRAN
END TRY
BEGIN CATCH
PRINT 'In CATCH Block'
IF(@@TRANCOUNT > 0)
ROLLBACK TRAN;
THROW; -- raise error to the client
END CATCH
PRINT 'After END CATCH'
SELECT * FROM dbo.Account WITH(NOLOCK)
GO
Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select
, and need to prepend a select
also to the list. Finally, you need to provide aliases for the table and column in you subselect:
Create Table #IMEIS(
imei varchar(15)
)
INSERT INTO #IMEIS(imei)
SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;
But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.
You can do the following(jackson version < 2):
Custom mapper class:
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
super.getSerializationConfig()
.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
super.getSerializationConfig()
.set(SerializationConfig.Feature.INDENT_OUTPUT, false);
}
}
Spring config:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="package.CustomObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
hi i got the same problem.. add 0.71 to excel cell width value and give that value to the
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
eg: A Column width = 3.71 (excel value)
give column width = 4.42
will give the output file with same cell width.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);
hope this help
You could use the ones on CodePlex or http://www.enterprisedt.com/general/press/20060818.html
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.
CREATE TABLE contacts
(contact_id BIGINT AUTO_INCREMENT NOT NULL,
name VARCHAR(75) NOT NULL,
PRIMARY KEY(contact_id)) ENGINE = InnoDB;
CREATE TABLE phone_numbers
(phone_id BIGINT AUTO_INCREMENT NOT NULL,
phone_number CHAR(10) NOT NULL,
contact_id BIGINT NOT NULL,
PRIMARY KEY(phone_id),
UNIQUE(phone_number)) ENGINE = InnoDB;
ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;
By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.
INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);
Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.
DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */
To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.
<?php
namespace Entities;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @Entity
* @Table(name="contacts")
*/
class Contact
{
/**
* @Id
* @Column(type="integer", name="contact_id")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string", length="75", unique="true")
*/
protected $name;
/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
*/
protected $phonenumbers;
public function __construct($name=null)
{
$this->phonenumbers = new ArrayCollection();
if (!is_null($name)) {
$this->name = $name;
}
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function addPhonenumber(Phonenumber $p)
{
if (!$this->phonenumbers->contains($p)) {
$this->phonenumbers[] = $p;
$p->setContact($this);
}
}
public function removePhonenumber(Phonenumber $p)
{
$this->phonenumbers->remove($p);
}
}
<?php
namespace Entities;
/**
* @Entity
* @Table(name="phonenumbers")
*/
class Phonenumber
{
/**
* @Id
* @Column(type="integer", name="phone_id")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string", length="10", unique="true")
*/
protected $number;
/**
* @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
* @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
*/
protected $contact;
public function __construct($number=null)
{
if (!is_null($number)) {
$this->number = $number;
}
}
public function setPhonenumber($number)
{
$this->number = $number;
}
public function setContact(Contact $c)
{
$this->contact = $c;
}
}
?>
<?php
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$contact = new Contact("John Doe");
$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1);
$contact->addPhonenumber($phone2);
$em->persist($contact);
try {
$em->flush();
} catch(Exception $e) {
$m = $e->getMessage();
echo $m . "<br />\n";
}
If you now do
# doctrine orm:schema-tool:create --dump-sql
you will see that the same SQL will be generated as in the first, raw-SQL example
the window.top
property should be able to give what you need.
E.g.
alert(top.location.href)
It's an ordinary Python list. The exception that you would catch for this is IndexError, but you're better off just checking the length instead.
if len(sys.argv) >= 2:
startingpoint = sys.argv[1]
else:
startingpoint = 'blah'
Use theme()
:
d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20),
axis.text.x = element_text(angle=90, hjust=1))
#vjust adjust the vertical justification of the labels, which is often useful
There's lots of good information about how to format your ggplots here. You can see a full list of parameters you can modify (basically, all of them) using ?theme
.
Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:
var result = {};
for ( let { first_field, ...fields } of your_data )
{
result[first_field] = result[first_field] || [];
result[first_field].push({ ...fields });
}
I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.
Try in html:
style="display: inline-block; margin-top: 50px;"
or in css:
display: inline-block;
margin-top: 50px;
Boomerang may also be worth checking out.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
you can use the zenity to displays the query output as html table.
first implement bash script with following code:
cat > '/tmp/sql.op'; zenity --text-info --html --filename='/tmp/sql.op';
save it like mypager.sh
Then export the environment variable PAGER by set full path of the script as value.
for example:- export PAGER='/path/mypager.sh'
Then login to the psql program then execute the command \H
And finally execute any query,the tabled output will displayed in the zenity in html table format.
Using ngClass
to disabled the button for invalid form is not good practice in Angular2 when its providing inbuilt features to enable and disable the button if form is valid and invalid respectively without doing any extra efforts/logic.
[disabled]
will do all thing like if form is valid then it will be enabled and if form is invalid then it will be disabled automatically.
See Example:
<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">
Use Callable
instead of Thread, then you can call Future#get()
which throws any exception that the Callable threw.
Distances to the source of iBeacon-formatted advertisement packets are estimated from the signal path attenuation calculated by comparing the measured received signal strength to the claimed transmit power which the transmitter is supposed to encode in the advertising data.
A path loss based scheme like this is only approximate and is subject to variation with things like antenna angles, intervening objects, and presumably a noisy RF environment. In comparison, systems really designed for distance measurement (GPS, Radar, etc) rely on precise measurements of propagation time, in same cases even examining the phase of the signal.
As Jiaru points out, 160 ft is probably beyond the intended range, but that doesn't necessarily mean that a packet will never get through, only that one shouldn't expect it to work at that distance.
Even there is an update in 4.3.0 API. ServiceRegistryBuilder is also deprecated in 4.3.0 and replaced with the StandardServiceRegistryBuilder. Now the actual code for creating the session factory would look this example on creating session factory.
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
Here is my solution in a recent project.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Sample</title>_x000D_
</head>_x000D_
<body>_x000D_
<h1 id="hello_world">Sample</h1>_x000D_
<script type="text/javascript">_x000D_
var div = document.createElement("div");_x000D_
var t = document.createElement('template');_x000D_
t.innerHTML = "Check Console tab for javascript output: Hello world!!!<br/><script type='text/javascript' >console.log('Hello world!!!');<\/script>";_x000D_
_x000D_
for (var i=0; i < t.content.childNodes.length; i++){_x000D_
var node = document.importNode(t.content.childNodes[i], true);_x000D_
div.appendChild(node);_x000D_
}_x000D_
document.body.appendChild(div);_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
This exception come due to you are providing listener ContextLoaderListener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
but you are not providing context-param
for your spring configuration file. like applicationContext.xml
You must provide below snippet for your configuration
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
If You are providing the java based spring configuration , means you are not using xml file for spring configuration at that time you must provide below code:
<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified @Configuration classes. Fully-qualified packages may also
be specified for component-scanning -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.nirav.modi.config.SpringAppConfig</param-value>
</context-param>
You are almost there. (note change in the return value of FindWindow declaration). I'd recommend using RegisterWindowMessage in this case so you don't have to worry about the ins and outs of WM_USER.
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, String lpWindowName);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
public void button1_Click(object sender, EventArgs e)
{
// this would likely go in a constructor because you only need to call it
// once per process to get the id - multiple calls in the same instance
// of a windows session return the same value for a given string
uint id = RegisterWindowMessage("MyUniqueMessageIdentifier");
IntPtr WindowToFind = FindWindow(null, "Form1");
Debug.Assert(WindowToFind != IntPtr.Zero);
SendMessage(WindowToFind, id, IntPtr.Zero, IntPtr.Zero);
}
And then in your Form1 class:
class Form1 : Form
{
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
private uint _messageId = RegisterWindowMessage("MyUniqueMessageIdentifier");
protected override void WndProc(ref Message m)
{
if (m.Msg == _messageId)
{
// do stuff
}
base.WndProc(ref m);
}
}
Bear in mind I haven't compiled any of the above so some tweaking may be necessary.
Also bear in mind that other answers warning you away from SendMessage
are spot on. It's not the preferred way of inter module communication nowadays and genrally speaking overriding the WndProc
and using SendMessage/PostMessage
implies a good understanding of how the Win32 message infrastructure works.
But if you want/need to go this route I think the above will get you going in the right direction.
d = {}
will create a new instance for d
but all other references will still point to the old contents.
d.clear()
will reset the contents, but all references to the same instance will still be correct.
Below illustrates XORing string s with m, and then again to reverse the process:
>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>
try this:
Use ´return false´ for to cut the flow of the event:
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
Edit
corroborate if the form element with the 'length' of jQuery:
alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
OR:
it waits for the DOM is ready:
jQuery(function() {
alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
});
Do you put your code inside the event "ready" the document or after the DOM is ready?
I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php
is calling config-db.php
** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1
/etc/phpmyadmin/config-db.php:
$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';
Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration.
That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
Assuming hash1
and hash2
List< String > sames = whatever
List< String > diffs = whatever
int count = 0;
for( String key : hash1.keySet() )
{
if( hash2.containsKey( key ) )
{
sames.add( key );
}
else
{
diffs.add( key );
}
}
//sames.size() contains the number of similar elements.
Without use of Reflection:
private T Create<T>() where T : class, new()
{
return new T();
}
You can set autoplay=""
<video width="640" height="480" controls="controls" type="video/mp4" autoplay="">
<source src="http://example.com/mytestfile.mp4">
Your browser does not support the video tag.
</video>
ps. for enabling you can use autoplay
or autoplay="autoplay"
In TS we can type functions in the in the following manners:
Functions types/signatures
This is used for real implementations of functions/methods it has the following syntax:
(arg1: Arg1type, arg2: Arg2type) : ReturnType
Example:
function add(x: number, y: number): number {
return x + y;
}
class Date {
setTime(time: number): number {
// ...
}
}
Function Type Literals
Function type literals are another way to declare the type of a function. They're usually applied in the function signature of a higher-order function. A higher-order function is a function which accepts functions as parameters or which returns a function. It has the following syntax:
(arg1: Arg1type, arg2: Arg2type) => ReturnType
Example:
type FunctionType1 = (x: string, y: number) => number;
class Foo {
save(callback: (str: string) => void) {
// ...
}
doStuff(callback: FunctionType1) {
// ...
}
}
After trying out every solution I could find:
npm config set strict-ssl=false
npm config set registry http://registry.npmjs.org/
npm config set cafile /path/to/your/cert.pem
set NODE_TLS_REJECT_UNAUTHORIZED=0
The solution that seems to be working the best for me now is to use the NODE_EXTRA_CA_CERTS environment variable which extends the existing CAs rather than replacing them with the cafile option in your .npmrc file. You can set it by entering this in your terminal: NODE_EXTRA_CA_CERTS=path/to/your/cert.pem
Of course, setting this variable every time can be annoying, so I added it to my bash profile so that it will be set every time I open terminal. If you don’t already have a ~/.bash_profile
file, create one. Then at the end of that file add export NODE_EXTRA_CA_CERTS=path/to/your/cert.pem
. Then, remove the cafile setting in your .npmrc.
If the type implements IDisposable, it automatically disposes that type.
Given:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
These are equivalent:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
The second is easier to read and maintain.
Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.
<div id="showhide" class="meta-info" onclick="changeclass(this);">
function changeclass(element) {
$(element).toggleClass('mynewclass');
}
Or for a slighly more jQuery way (you would run this after the DOM is loaded)
<div id="showhide" class="meta-info">
$('#showhide').click(function() {
$(this).toggleClass('mynewclass');
});
See a working example of this here: http://jsfiddle.net/S76WN/
This exception can be solved by specifying a full class path.
Example:
If you are using a class named ExceptionDetails
Wrong Way of passing arguments
JAXBContext jaxbContext = JAXBContext.newInstance(ExceptionDetails.class);
Right Way of passing arguments
JAXBContext jaxbContext = JAXBContext.newInstance(com.tibco.schemas.exception.ExceptionDetails.class);
If you want to call a bash script using python, here is a simple method to load a file from a folder in S3 bucket to a local folder (in a Linux machine) :
import boto3
import subprocess
import os
###TOEDIT###
my_bucket_name = "your_my_bucket_name"
bucket_folder_name = "your_bucket_folder_name"
local_folder_path = "your_local_folder_path"
###TOEDIT###
# 1.Load thes list of files existing in the bucket folder
FILES_NAMES = []
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('{}'.format(my_bucket_name))
for object_summary in my_bucket.objects.filter(Prefix="{}/".format(bucket_folder_name)):
# print(object_summary.key)
FILES_NAMES.append(object_summary.key)
# 2.List only new files that do not exist in local folder (to not copy everything!)
new_filenames = list(set(FILES_NAMES )-set(os.listdir(local_folder_path)))
# 3.Time to load files in your destination folder
for new_filename in new_filenames:
upload_S3files_CMD = """aws s3 cp s3://{}/{}/{} {}""".format(my_bucket_name,bucket_folder_name,new_filename ,local_folder_path)
subprocess_call = subprocess.call([upload_S3files_CMD], shell=True)
if subprocess_call != 0:
print("ALERT: loading files not working correctly, please re-check new loaded files")
public class XMLParser {
public static void main(String[] args){
try {
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(new File("xml input"));
NodeList nl=doc.getDocumentElement().getChildNodes();
for(int k=0;k<nl.getLength();k++){
printTags((Node)nl.item(k));
}
} catch (Exception e) {/*err handling*/}
}
public static void printTags(Node nodes){
if(nodes.hasChildNodes() || nodes.getNodeType()!=3){
System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
NodeList nl=nodes.getChildNodes();
for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
}
}
}
Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.
Other answers provide pretty concise answer to this, without one important fact: You don't need to implement fixed point combinator in any practical language in this convoluted way and doing so serves no practical purpose (except "look, I know what Y-combinator is"). It's important theoretical concept, but of little practical value.
No need for a separate SELECT...
INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');
This works for non-IDENTITY columns (such as GUIDs) too