Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.
In ES6, the includes()
method is used to determine whether one string may be found within another string, returning true
or false
as appropriate.
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
console.log(str.includes('question')); // true
console.log(str.includes('nonexistent')); // false
Here is jsperf between
var ret = str.includes('one');
And
var ret = (str.indexOf('one') !== -1);
As the result shown in jsperf, it seems both of them perform well.
As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach
function.
var element = $('#childNode').detach();
$('#parentNode').append(element);
Edit:
Igor Mukhin suggested an even shorter version in the comments below:
$("#childNode").detach().appendTo("#parentNode");
I've used something like this before:
public static T CreateFromString<T>(string stringToCreateFrom) {
T output = Activator.CreateInstance<T>();
if (!output.GetType().IsEnum)
throw new IllegalTypeException();
try {
output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
}
catch (Exception ex) {
string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
_logger.Error(error, ex);
throw new IllegalArgumentException(error, ex);
}
return output;
}
write main.c like this -
caution : while linking both main.0 and ClasseAusiliaria.o should be
available to linker.
#include <stdlib.h>
#include <stdio.h>
extern int addizione(int a, int b)
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
I'm using jQuery and JavaScript and it works fine for me:
var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(rege.test($('#uemail').val())){ //do something }
Remove the last commit before push
git reset --soft HEAD~1
1
means the last commit, if you want to remove two last use 2
, and so forth*
I personally think that sizeof(a) / sizeof(*a) looks cleaner.
I also prefer to define it as a macro:
#define NUM(a) (sizeof(a) / sizeof(*a))
Then you can use it in for-loops, thusly:
for (i = 0; i < NUM(a); i++)
The nil pointer dereference is in line 65 which is the defer in
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
If err!= nil then res==nil and res.Body panics. Handle err before defering the res.Body.Close().
To understand the difference between a simulator and an emulator, keep in mind that a simulator tries to mimic the behavior of a real device. For example, in the case of the iOS Simulator, it simulates the real behavior of an actual iPhone/iPad device. However, the Simulator itself uses the various libraries installed on the Mac (such as QuickTime) to perform its rendering so that the effect looks the same as an actual iPhone. In addition, applications tested on the Simulator are compiled into x86 code, which is the byte-code understood by the Simulator. A real iPhone device, conversely, uses ARM-based code.
In contrast, an emulator emulates the working of a real device. Applications tested on an emulator are compiled into the actual byte-code used by the real device. The emulator executes the application by translating the byte-code into a form that can be executed by the host computer running the emulator.
To understand the subtle difference between simulation and emulation, imagine you are trying to convince a child that playing with knives is dangerous. To simulate this, you pretend to cut yourself with a knife and groan in pain. To emulate this, you actually cut yourself.
The default modifier is package
. Only code in the same package will be able to invoke this constructor.
You are trying to min-max scale the values of audio
between -1 and +1 and image
between 0 and 255.
Using sklearn.preprocessing.minmax_scale
, should easily solve your problem.
e.g.:
audio_scaled = minmax_scale(audio, feature_range=(-1,1))
and
shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)
note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.
If a
is a prime then the while x:
in your code will run forever, since x
will remain True
.
So why is that while
there?
I think you wanted to end the for loop when you found a factor, but didn't know how, so you added that while since it has a condition. So here is how you do it:
def is_prime(a):
x = True
for i in range(2, a):
if a%i == 0:
x = False
break # ends the for loop
# no else block because it does nothing ...
if x:
print "prime"
else:
print "not prime"
Use forward slashes. See explanation here
It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.
You can use the following approach.
$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
//...
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach
In your case you already have the data within the $query
variable.
For only to display, property of String
can be used as following..
double value = 123.456789;
String.Format("{0:0.00}", value);
Using System.Math.Round
. This value can be assigned to others or manipulated as required..
double value = 123.456789;
System.Math.Round(value, 2);
To see the keys:
for key in d.keys():
print(key)
To get the values that each key is referencing:
for key in d.keys():
print(d[key])
Add to a list:
for key in d.keys():
mylist.append(d[key])
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('ddd');
console.log(weekDayName);
Result: Wed
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
Result: Wednesday
I was able to Do it using the U (Underline Tag)
u {
text-decoration: none;
position: relative;
}
u:after {
content: '';
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
<a href="" style="text-decoration:none">
<div style="text-align: right; color: Red;">
<u> Shop Now</u>
</div>
</a>
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):
// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
// Replace 8000, below, with the correct size of the field
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
cmd.ExecuteNonQuery();
}
Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with
For the record:
"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".
For all files (default setting for opened file): Settings/Preferences | Editor | General | Use soft wraps in editor
For currently opened file in editor: Menu | View | Active Editor | Use Soft Wraps
In latest IDE versions you can also access this option via context menu for the editor gutter area (the area with line numbers on the left side of the editor).
Search Everywhere
(Shift 2x times) or Help | Find Action...
( Ctrl + Shift+ A on Windows using Default keymap) can also be used to quickly change this option (instead of going into Settings/Preferences).
You can add line-height:51px
to #AlertDiv h1
if you know it's only ever going to be one line. Also add text-align:center
to #AlertDiv
.
#AlertDiv {
top:198px;
left:365px;
width:62px;
height:51px;
color:white;
position:absolute;
text-align:center;
background-color:black;
}
#AlertDiv h1 {
margin:auto;
line-height:51px;
vertical-align:middle;
}
The demo below also uses negative margins to keep the #AlertDiv
centered on both axis, even when the window is resized.
Demo: jsfiddle.net/KaXY5
Try this code:
final List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");
final String[] str = {"Report 1", "Report 2", "Report 3", "Report 4", "Report 5"};
final Spinner sp1 = (Spinner) findViewById(R.id.spinner1);
final Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);
ArrayAdapter<String> adp2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, str);
adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adp2);
sp1.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), list.get(position), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str[position], Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
You can also add spinner item value through String array xml file..
<resources>
<string name="app_name">Spinner_ex5</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string-array name="str2">
<item>Data 1</item>
<item>Data 2</item>
<item>Data 3</item>
<item>Data 4</item>
<item>Data 5</item>
</string-array>
</resources>
In mainActivity.java:
final Spinner sp3 = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource(this,
R.array.str2, android.R.layout.simple_list_item_1);
adp3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adp3);
sp3.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
String ss = sp3.getSelectedItem().toString();
Toast.makeText(getBaseContext(), ss, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
This also works:
db.Account.find().sort('UserName', -1)
db.Account.find().sort('UserName', 1)
I'm using this in my code, please comment if i'm doing something wrong here, thanks.
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
First go to the directory where your python script is present by using-
cd path/to/directory
then simply do:
python file_name.py
Basic validation can be performed by choosing the type attribute of input elements. For example:
<input type="email" />
<input type="URL" />
<input type="number" />
using pattern attribute like:
<input type="text" pattern="[1-4]{5}" />
required attribute
<input type="text" required />
maxlength:
<input type="text" maxlength="20" />
min & max:
<input type="number" min="1" max="4" />
Oh you can definitely use try catch to check whether its or not a valid JSON
Tested on Firfox Quantom 60.0.1
use function inside a function to get the JSON tested and use that output to validate the string. hears an example.
function myfunction(text){
//function for validating json string
function testJSON(text){
try{
if (typeof text!=="string"){
return false;
}else{
JSON.parse(text);
return true;
}
}
catch (error){
return false;
}
}
//content of your real function
if(testJSON(text)){
console.log("json");
}else{
console.log("not json");
}
}
//use it as a normal function
myfunction('{"name":"kasun","age":10}')
In essence, many things can go wrong in a multi threaded environment (instructions reordering, partially constructed objects, same variable having different values in different threads because of caching at the CPU level etc.).
I like the definition given by Java Concurrency in Practice:
A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
By correctly they mean that the program behaves in compliance with its specifications.
Contrived example
Imagine that you implement a counter. You could say that it behaves correctly if:
counter.next()
never returns a value that has already been returned before (we assume no overflow etc. for simplicity)A thread safe counter would behave according to those rules regardless of how many threads access it concurrently (which would typically not be the case of a naive implementation).
You can also look in the init script area (e.g. centos vi /etc/init.d/jenkins ) for details on how the service is actually started and stopped.
Works on all browsers, this is all you need.
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:
$('#elementID').html(commaSeparateNumber(1234567890));
or
$('#inputID').val(commaSeparateNumber(1234567890));
use
statusCode: {
404: function() {
alert('page not found');
}
}
-
$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},
400: function() {
alert('bad request');
}
}
});
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
If you want that image to be zoomed on mouse hover :
$(document).ready( function() {
$('#div img').hover(
function() {
$(this).animate({ 'zoom': 1.2 }, 400);
},
function() {
$(this).animate({ 'zoom': 1 }, 400);
});
});
?or you may do like this if zoom in and out buttons are used :
$("#ZoomIn").click(ZoomIn());
$("#ZoomOut").click(ZoomOut());
function ZoomIn (event) {
$("#div img").width(
$("#div img").width() * 1.2
);
$("#div img").height(
$("#div img").height() * 1.2
);
},
function ZoomOut (event) {
$("#div img").width(
$("#imgDtls").width() * 0.5
);
$("#div img").height(
$("#div img").height() * 0.5
);
}
The problem was that clicking the anchor still triggered a click in your <div>
. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading
which also have #ancherComplaint
as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Those two requires aren't equivalent. The equivalent version of the first one would be:
SELECT sum(numbackends) FROM pg_stat_database;
In that case, I would expect that version to be slightly faster than the second one, simply because it has fewer rows to count. But you are not likely going to be able to measure a difference.
Both queries are based on exactly the same data, so they will be equally accurate.
You can use this example without using temp table:
DECLARE
l_var VARCHAR2(32767); -- max length
BEGIN
FOR rec IN (SELECT ID, LONG_COLUMN FROM TABLE_WITH_LONG_COLUMN) LOOP
l_var := rec.LONG_COLUMN;
IF l_var LIKE '%350%' THEN -- is there '350' string?
dbms_output.put_line('ID:' || rec.ID || ' COLUMN:' || rec.LONG_COLUMN);
END IF;
END LOOP;
END;
Of course there is a problem if LONG has more than 32K characters.
.toggleClass()
will not animate, you should go for slideToggle()
or .animate()
method.
A small change to Paul's code so that it doesn't return the error mentioned above.
dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +
geom_point() + geom_line()
The best way to find out the REAL type of an object (including BOTH the native Object or DataType name (such as String, Date, Number, ..etc) AND the REAL type of an object (even custom ones); is by grabbing the name property of the object prototype's constructor:
Native Type Ex1:
var string1 = "Test";
console.log(string1.__proto__.constructor.name);
displays:
String
Ex2:
var array1 = [];
console.log(array1.__proto__.constructor.name);
displays:
Array
Custom Classes:
function CustomClass(){_x000D_
console.log("Custom Class Object Created!");_x000D_
}_x000D_
var custom1 = new CustomClass();_x000D_
_x000D_
console.log(custom1.__proto__.constructor.name);
_x000D_
displays:
CustomClass
If you're happy to require 'active_support/core_ext'
, then you can use
DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800
CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml
file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.
This problem is because of your https that means SSL certification. Try on Localhost.
class a(object):
def my_hello(self):
print "hello ravi"
class b(a):
def my_hello(self):
super(b,self).my_hello()
print "hi"
obj = b()
obj.my_hello()
I was scratching my head about this for a while too, and since Dave's explanation is a little hard to understand I'll post my (apparently working) code:
private class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
mFragment=mActivity.getFragmentManager().findFragmentByTag(mTag);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(android.R.id.content, mFragment, mTag);
} else {
if (mFragment.isDetached()) {
ft.attach(mFragment);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
As you can see it's pretty much like the Android sample, apart from not detaching in the constructor, and using replace instead of add.
After much headscratching and trial-and-error I found that finding the fragment in the constructor seems to make the double onCreateView problem magically go away (I assume it just ends up being null for onTabSelected when called through the ActionBar.setSelectedNavigationItem() path when saving/restoring state).
To use ASCII with accents:
var str = str.replace(/[^\x00-\xFF]/g, "");
You can parse the date using the Date
constructor, then spit out the individual time components:
function convert(str) {_x000D_
var date = new Date(str),_x000D_
mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
day = ("0" + date.getDate()).slice(-2);_x000D_
return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:
function convert(str) {_x000D_
var mnths = {_x000D_
Jan: "01",_x000D_
Feb: "02",_x000D_
Mar: "03",_x000D_
Apr: "04",_x000D_
May: "05",_x000D_
Jun: "06",_x000D_
Jul: "07",_x000D_
Aug: "08",_x000D_
Sep: "09",_x000D_
Oct: "10",_x000D_
Nov: "11",_x000D_
Dec: "12"_x000D_
},_x000D_
date = str.split(" ");_x000D_
_x000D_
return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
Yes, you could use either the JavaScript setTimeout()
method or setInterval()
method to invoke the code that you would like to run. Here's how you might do it with setTimeout:
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
I created this VERY SIMPLE and basic plugin:
(function($){
$.fn.extend({
bs_alert: function(message, title){
var cls='alert-danger';
var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
if(typeof title!=='undefined' && title!==''){
html+='<h4>'+title+'</h4>';
}
html+='<span>'+message+'</span></div>';
$(this).html(html);
},
bs_warning: function(message, title){
var cls='alert-warning';
var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
if(typeof title!=='undefined' && title!==''){
html+='<h4>'+title+'</h4>';
}
html+='<span>'+message+'</span></div>';
$(this).html(html);
},
bs_info: function(message, title){
var cls='alert-info';
var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
if(typeof title!=='undefined' && title!==''){
html+='<h4>'+title+'</h4>';
}
html+='<span>'+message+'</span></div>';
$(this).html(html);
}
});
})(jQuery);
Usage is
<div id="error_container"></div>
<script>
$('#error_container').bs_alert('YOUR ERROR MESSAGE HERE !!', 'title');
</script>
first plugin EVER and it can be easily made better
If you are using gcc, you can use the GNU-extension a
specifier to have scanf() allocate memory for you to hold the input:
int main()
{
char *str = NULL;
scanf ("%as", &str);
if (str) {
printf("\"%s\"\n", str);
free(str);
}
return 0;
}
Edit: As Jonathan pointed out, you should consult the scanf
man pages as the specifier might be different (%m
) and you might need to enable certain defines when compiling.
>
selects all direct descendants/childrenA space selector will select all deep descendants whereas a greater than
>
selector will only select all immediate descendants. See fiddle for example.
div { border: 1px solid black; margin-bottom: 10px; }_x000D_
.a b { color: red; } /* every John is red */_x000D_
.b > b { color: blue; } /* Only John 3 and John 4 are blue */
_x000D_
<div class="a">_x000D_
<p><b>John 1</b></p>_x000D_
<p><b>John 2</b></p>_x000D_
<b>John 3</b>_x000D_
<b>John 4</b>_x000D_
</div>_x000D_
_x000D_
<div class="b">_x000D_
<p><b>John 1</b></p>_x000D_
<p><b>John 2</b></p>_x000D_
<b>John 3</b>_x000D_
<b>John 4</b>_x000D_
</div>
_x000D_
TL;DR No, it can't be done automatically. Yes, it is possible.
import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))
Each plot (axes
) in a figure (figure
) has its own cycle of colors — if you don't force a different color for each plot, all the plots share the same order of colors but, if we stretch a bit what "automatically" means, it can be done.
The OP wrote
[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].
But... Matplotlib automatically generates different colors for each different curve
In [10]: import numpy as np
...: import matplotlib.pyplot as plt
In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:
So why the OP request? If we continue to read, we have
Can you please give me a method to put different colors for different plots in the same figure?
and it make sense, because each plot (each axes
in Matplotlib's parlance) has its own color_cycle
(or rather, in 2018, its prop_cycle
) and each plot (axes
) reuses the same colors in the same order.
In [12]: fig, axes = plt.subplots(2,3)
In [13]: for ax in axes.flatten():
...: ax.plot((0,1), (0,1))
If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.
If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by Matplotlib.
In [14]: fig, axes = plt.subplots(2,3)
In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
...: ax.plot((0,1), (0,1), short_color_name)
Another possibility is to instantiate a cycler object
from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()
fig, axes = plt.subplots(2,3)
for ax in axes.flat:
ax.plot((0,1), (0,1), **next(actual_cycler))
Note that type(my_cycler)
is cycler.Cycler
but type(actual_cycler)
is itertools.cycle
.
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
All the above is nice, but if you need to
then the following trick is the one and only way.
First learn how to create spool files or export result sets from the source db command line client. Second learn how to execute sql statements on the destination db.
Finally, create the insert statements (and any other statements) for the destination database by running an sql script on the source database. e.g.
SELECT '-- SET the correct schema' FROM dual;
SELECT 'USE test;' FROM dual;
SELECT '-- DROP TABLE IF EXISTS' FROM dual;
SELECT 'IF OBJECT_ID(''table3'', ''U'') IS NOT NULL DROP TABLE dbo.table3;' FROM dual;
SELECT '-- create the table' FROM dual;
SELECT 'CREATE TABLE table3 (column1 VARCHAR(10), column2 VARCHAR(10));' FROM dual;
SELECT 'INSERT INTO table3 (column1, column2) VALUES (''', table1.column1, ''',''', table2.column2, ''');' FROM table1 JOIN table2 ON table2.COLUMN1 = table1.COLUMN1;
The above example was created for Oracle's db where the use of dual is needed for table-less selects.
The result set will contain the script for the destination db.
I had the same problem. A simple service docker restart
solved the problem.
import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)
std::queue<myclass*> my_queue;
will do the job.
See here for more information on this container.
In SQL Server 2008 you can use
http://www.sommarskog.se/share_data.html#tableparam
or else simple and same as common execution
CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS
SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID
SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]
RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO
I hopes its help to you
Python is not strongly typed in the sense of static or compile-time type checking.
Most Python code falls under so-called "Duck Typing" -- for example, you look for a method read
on an object -- you don't care if the object is a file on disk or a socket, you just want to read N bytes from it.
If you are using TextEditingController then set the text to it, like below
TextEditingController _controller = new TextEditingController();
_controller.text = 'your initial text';
final your_text_name = TextFormField(
autofocus: false,
controller: _controller,
decoration: InputDecoration(
hintText: 'Hint Value',
),
);
and if you are not using any TextEditingController then you can directly use initialValue like below
final last_name = TextFormField(
autofocus: false,
initialValue: 'your initial text',
decoration: InputDecoration(
hintText: 'Last Name',
),
);
For more reference TextEditingController
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
Also to shed some light, it is important to know that var-arg parameters are limited to one and you can't have several var-art params. For example this is illigal:
public void myMethod(String... strings, int ... ints){
// method body
}
You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<systemPropertyVariables>
<java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs>
<log4j.configuration>log4j-core.properties</log4j.configuration>
</systemPropertyVariables>
</configuration>
</plugin>
http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html
xargs --arg-file inputfile cat
This will output the filename followed by the file's contents:
xargs --arg-file inputfile -I % sh -c "echo %; cat %"
Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
@Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}
private boolean isConnectedToInternet(Context context) {
try {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
return false;
} catch (Exception e) {
Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
return false;
}
}
}
I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
}
}, intentFilter);
}
}
Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.
There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.
If you're using SQL Server, you can set the value of bit fields with 0 and 1
or
'true' and 'false'
(yes, using strings)
...your_bit_field='false'... => equivalent to 0
Instead of concatenating paths like in some answers, I use File.expand_path
:
Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
require file
end
Update:
Instead of using File.dirname
you could do the following:
Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
require file
end
Where ..
strips the filename of __FILE__
.
you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-
inline-elements :- <img style="vertical-align:middle" ...>
<span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>
block-elements :- <td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
see the demo:- http://jsfiddle.net/Ewfkk/2/
>>> a = 255556
>>> a == 255556
True
>>> a is 255556
False
I think that should answer it ;-)
The reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is
, they are not the same.
I too faced the same problem, and I did a "Factory data reset", and it worked fine after that.
vb.net version
Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)
You've added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException
, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn't valid, for example) and a failure within the method called.
Just unwrap the cause within the InvocationTargetException
and you'll get to the original one.
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
Have a read through this blog post with an example of transition animations, I've included the code below:
package com.as400samplecode;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button nextActivity = (Button) findViewById(R.id.nextActivity);
nextActivity.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.nextActivity:
Intent nextActivity = new Intent(this,NextActivity.class);
startActivity(nextActivity);
//push from bottom to top
overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
//slide from right to left
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
break;
// More buttons go here (if any) ...
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity"
android:background="@color/ivory">
<Button android:id="@+id/nextActivity" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginTop="15dp"
android:text="Go to Next Activity" />
</RelativeLayout>
package com.as400samplecode;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class NextActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
Button previousActivity = (Button) findViewById(R.id.previousActivity);
previousActivity.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.previousActivity:
finish();
//push from top to bottom
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
//slide from left to right
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
break;
// More buttons go here (if any) ...
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".NextActivity"
android:background="@color/khaki">
<Button android:id="@+id/previousActivity" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginTop="15dp"
android:text="Go to Previous Activity" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="5000"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="5000" />
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="5000"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="5000"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="-100%" android:toXDelta="0%"/>
<alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="100%" android:toXDelta="0%" />
<alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="-100%"/>
<alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="100%"/>
<alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>
The reason is that your rule
%.o: %.cpp
...
expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.
You can use VPATH to resolve this:
VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:
$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
Where "$<" expands to the path where make located the first dependency.
Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like
build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:
define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
You can then have multiple rules like this:
build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
Compatibility with older browsers can be a drag, so be adviced.
If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.
Change left and right values to meet your requirement.
Thank you.
Hope this helps.
#container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
flex: 1;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
background: orange;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="column left">this is left</div>_x000D_
<div class="column center">this is center</div>_x000D_
<div class="column right">this is right</div>_x000D_
</div>
_x000D_
Not relevant to the onclick issue, but also related:
For html attributes whose name collide with javascript reserved words, an alternate name is chosen, eg. <div class=''>
, but div.className
, or <label for='...'>
, but label.htmlFor
.
In reasonable browsers, this doesn't affect setAttribute
. So in gecko and webkit you'd call div.setAttribute('class', 'foo')
, but in IE you have to use the javascript property name instead, so div.setAttribute('className', 'foo')
.
For anyone else getting
Nginx 403 error: directory index of [folder] is forbidden
when using index.php
while index.html
works perfectly and having included index.php
in the index in the server block of their site config in sites-enabled
server {
listen 80;
# this path MUST be exactly as docker-compose php volumes
root /usr/share/nginx/html;
index index.php
...
}
Make sure your nginx.conf file at /etc/nginx/nginx.conf
actually loads your site config in the http
block...
http {
...
include /etc/nginx/conf.d/*.conf;
# Load our websites config
include /etc/nginx/sites-enabled/*;
}
This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:
select *
from issues
where issueid not in (
select top (
(select count(*) from issues) - 5
) issueid
from issues
)
Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.
The bootstrap css used in the jsfiddle link, dont have the css for col-xs-offset-*, thats why the css are not been applied. Refer the latest bootstrap css.
From PHP's manual :
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
So you have it. The error message is not really helpful, I give you that though.
PHP7 introduced more function data type declarations, and the aforementioned link has been moved to Function arguments : Type declarations. From that page :
Valid types
Warning
Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:
<?php function test(boolean $param) {} test(true); ?>
The above example will output:
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
The last warning is actually significant to understand the error "Argument must of type string, string given"; since mostly only class/interface names are allowed as argument type, PHP tries to locate a class name "string", but can't find any because it is a primitive type, thus fail with this awkward error.
I am not sure if I see this option here. You can just create a /folder
in your repository and use it directly:
[a relative link](/folder/myrelativefile.md)
No blob or tree or repository name is needed, and it works like a charm.
I know this is an old question, but someone should have mentioned the compile-time macros in Availability.h
. All of the other methods here are runtime solutions, and will not work in a header file, class category, or ivar definition.
For these situations, use
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
// iOS 6+ code here
#else
// Pre iOS 6 code here
#endif
h/t this answer
Since today I know it: the best thing for text extraction from PDFs is TET, the text extraction toolkit. TET is part of the PDFlib.com family of products.
PDFlib.com is Thomas Merz's company. In case you don't recognize his name: Thomas Merz is the author of the "PostScript and PDF Bible".
TET's first incarnation is a library. That one can probably do everything Budda006 wanted, including positional information about every element on the page. Oh, and it can also extract images. It recombines images which are fragmented into pieces.
pdflib.com also offers another incarnation of this technology, the TET plugin for Acrobat. And the third incarnation is the PDFlib TET iFilter. This is a standalone tool for user desktops. Both these are free (as in beer) to use for private, non-commercial purposes.
And it's really powerful. Way better than Adobe's own text extraction. It extracted text for me where other tools (including Adobe's) do spit out garbage only.
I just tested the desktop standalone tool, and what they say on their webpage is true. It has a very good commandline. Some of my "problematic" PDF test files the tool handled to my full satisfaction.
This thing will from now on be my recommendation for every sophisticated and challenging PDF text extraction requirements.
TET is simply awesome. It detects tables. Inside tables, it identifies cells spanning multiple columns. It identifies table rows and contents of each table cell separately. It deals very well with hyphenations: it removes hyphens and restores complete words. It supports non-ASCII languages (including CJK, Arabic and Hebrew). When encountering ligatures, it restores the original characters...
Give it a try.
Here's a C# example I just cooked up, loosely based on the answer using CSS selectors, hopefully of use to others for seeing how to setup a ReadOnlyCollection
of table rows and iterate over it in MS land at least. I'm looking through a collection of table rows to find a row with an OriginatorsRef
(just a string) and a TD
with an image that contains a title attribute with Overdue by
in it:
public ReadOnlyCollection<IWebElement> GetTableRows()
{
this.iwebElement = GetElement();
return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
}
And within my main code:
...
ReadOnlyCollection<IWebElement> TableRows;
TableRows = f.Grid_Fault.GetTableRows();
foreach (IWebElement row in TableRows)
{
if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
return true;
}
I have a much more effective solution which does not need scaling of any sort. Simply decode your bitmap only once and then cache it in a map against its name. Then simply retrieve the bitmap against the name and set it in the ImageView. There is nothing more that needs to be done.
This will work because the actual binary data of the decoded bitmap is not stored within the dalvik VM heap. It is stored externally. So every time you decode a bitmap, it allocates memory outside of VM heap which is never reclaimed by GC
To help you better appreciate this, imagine you have kept ur image in the drawable folder. You just get the image by doing a getResources().getDrwable(R.drawable.). This will NOT decode your image everytime but re-use an already decoded instance everytime you call it. So in essence it is cached.
Now since your image is in a file somewhere (or may even be coming from an external server), it is YOUR responsibility to cache the decoded bitmap instance to be reused any where it is needed.
Hope this helps.
The easiest way that I have found to get the correct date is using datejs.
I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'
var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);
Console will read:
Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)
Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)
https://jsfiddle.net/vp1ena7b/3/
The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.
I thought that this might help someone...
have you checked RSE (Remote System Explorer) ? I think it's pretty close to what you want to achieve.
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.
// A list may come from an API JSON like
{
"names": [
"Person 1",
"Person 2",
"Person 3",
...
"Person N"
]
}
var listOfNames = mutableListOf<String>()
val stringOfNames = listOfNames.joinToString(", ")
// ", " <- a separator for the strings, could be any string that you want
// Posible result
// Person 1, Person 2, Person 3, ..., Person N
This is useful for concatenating list of strings with separator.
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects
. So, you create a blank array. Create an object for each input
by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}]
There are a number of ways to get information on the attributes of your DataFrame or Series.
Create Sample DataFrame and Series
df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df
a b
0 5.0 9
1 2.0 2
2 NaN 4
s = df['a']
s
0 5.0
1 2.0
2 NaN
Name: a, dtype: float64
shape
AttributeThe shape
attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.
df.shape
(3, 2)
s.shape
(3,)
len
functionTo get the number of rows of a DataFrame or get the length of a Series, use the len
function. An integer will be returned.
len(df)
3
len(s)
3
size
attributeTo get the total number of elements in the DataFrame or Series, use the size
attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len
function:
df.size
6
s.size
3
ndim
attributeThe ndim
attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:
df.ndim
2
s.ndim
1
count
methodThe count
method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.
df.count() # by default, get the count of each column
a 2
b 3
dtype: int64
df.count(axis='columns') # change direction to get count of each row
0 2
1 2
2 1
dtype: int64
For a Series, there is only one axis for computation and so it just returns a scalar:
s.count()
2
info
method for retrieving metadataThe info
method returns the number of non-missing values and data types of each column
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a 2 non-null float64
b 3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
I worked through some of these samples and found they were lacking in some cases. This version works with all kinds of generics: types, interfaces and type definitions thereof.
public static bool InheritsOrImplements(this Type child, Type parent)
{
parent = ResolveGenericTypeDefinition(parent);
var currentChild = child.IsGenericType
? child.GetGenericTypeDefinition()
: child;
while (currentChild != typeof (object))
{
if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
return true;
currentChild = currentChild.BaseType != null
&& currentChild.BaseType.IsGenericType
? currentChild.BaseType.GetGenericTypeDefinition()
: currentChild.BaseType;
if (currentChild == null)
return false;
}
return false;
}
private static bool HasAnyInterfaces(Type parent, Type child)
{
return child.GetInterfaces()
.Any(childInterface =>
{
var currentInterface = childInterface.IsGenericType
? childInterface.GetGenericTypeDefinition()
: childInterface;
return currentInterface == parent;
});
}
private static Type ResolveGenericTypeDefinition(Type parent)
{
var shouldUseGenericType = true;
if (parent.IsGenericType && parent.GetGenericTypeDefinition() != parent)
shouldUseGenericType = false;
if (parent.IsGenericType && shouldUseGenericType)
parent = parent.GetGenericTypeDefinition();
return parent;
}
Here are the unit tests also:
protected interface IFooInterface
{
}
protected interface IGenericFooInterface<T>
{
}
protected class FooBase
{
}
protected class FooImplementor
: FooBase, IFooInterface
{
}
protected class GenericFooBase
: FooImplementor, IGenericFooInterface<object>
{
}
protected class GenericFooImplementor<T>
: FooImplementor, IGenericFooInterface<T>
{
}
[Test]
public void Should_inherit_or_implement_non_generic_interface()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(IFooInterface)), Is.True);
}
[Test]
public void Should_inherit_or_implement_generic_interface()
{
Assert.That(typeof(GenericFooBase)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void Should_inherit_or_implement_generic_interface_by_generic_subclass()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void Should_inherit_or_implement_generic_interface_by_generic_subclass_not_caring_about_generic_type_parameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void Should_not_inherit_or_implement_generic_interface_by_generic_subclass_not_caring_about_generic_type_parameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<int>)), Is.False);
}
[Test]
public void Should_inherit_or_implement_non_generic_class()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
[Test]
public void Should_inherit_or_implement_any_base_type()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
For those that are not overflowing but hiding by negative margin:
$('#element').height() + -parseInt($('#element').css("margin-top"));
(ugly but only one that works so far)
Assuming you did not commit the file, or add it to the index, then:
git checkout -- filename
Assuming you added it to the index, but did not commit it, then:
git reset HEAD filename
git checkout -- filename
Assuming you did commit it, then:
git checkout origin/master filename
Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):
git reset --hard origin/master
If you know, that your results implements a certain interface you could use the interface as datatype:
public void LogEmployees<T>(IEnumerable<T> list)
{
foreach (T item in list)
{
}
}
Use:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
Always use the above command to enable to executing PowerShell in the current session.
Folks, here's why you should use 1px instead of 1dp or 1dip: if you specify 1dp or 1dip, Android will scale that down. On a 120dpi device, that becomes something like 0.75px translated, which rounds to 0. On some devices, that translates to 2-3 pixels, and it usually looks ugly or sloppy
For dividers, 1px is the correct height if you want a 1 pixel divider and is one of the exceptions for the "everything should be dip" rule. It'll be 1 pixel on all screens. Plus, 1px usually looks better on hdpi and above screens
"It's not 2012 anymore" edit: you may have to switch over to dp/dip starting at a certain screen density
The alternative for explode in php is split.
The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
>>> "Rajasekar SP".split()
['Rajasekar', 'SP']
>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']
Check mvn dependency:tree
and see if there are multiple repos from where slf4j belongs to two different JARs.
If so, add exclusion in one of the dependencies:
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
df =df['Date'].dt.dayofweek
dayofweek
is in numeric format
You can use this to get a name of any provided member:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
To get name of a variable:
string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
To get name of a parameter:
public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}
You can use the nameof operator for parameters, variables and properties alike:
string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);
var quit = false;
function something() {
if(quit) {
return;
}
quit = true;
... other code....
}
var yesterday = DateTime.Now.AddDays(-1);
You have to add empty option to solve it,
I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.
<select onChange="jsFunction()" id="selectOpt">
<option value="1" onclick="jsFunction()">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
alert(myselect.options[myselect.selectedIndex].value);
}
You can dump a query as csv like this:
SELECT * from myTable
INTO OUTFILE '/tmp/querydump.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:
$one="909";
for($i=0;$i<10;$i++)
echo ' '.$one[$i];
will show the error. first case u can take the mod of i.. for example
function mod($i,$length){
$m = $i % $size;
if ($m > $size)
mod($m,$size)
return $m;
}
for($i=0;$i<10;$i++)
{
$k=mod($i,3);
echo ' '.$one[$k];
}
or might be it not an array (maybe it was a value and you tried to access it like an array) for example:
$k = 2;
$k[0];
Well, getting full path is not possible but we can have a temporary path.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
Most easy and clean solution to avoid this is adding onclick="return false;"
to a
tag.
<ul class="nav nav-tabs">
<li class="active">
<a href="#home" onclick="return false;">Home</a>
</li>
<li>
<a href="#ApprovalDetails" onclick="return false;">Approval Details</a>
</li>
</ul>
"cursor:no-drop;"
just makes cursor look disabled, but is clickable, Url gets appending with href target for ex page.apsx#Home
"disabled"
class to <li>
AND removing href
1) For me that's the most simple way passing parameters to async task is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
Try this, with strings:
set "var=string1string2string3"
and with string variables:
set "var=%string1%%string2%%string3%"
Check the column collation. This script might change the collation to the table default. Add the current collation to the script.
Or you might have something like this (redeclaring a variable):
var data = [];
var data =
../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.
Just for fun (new lambda functions):
static std::list<string> some_list;
vector<string> s;
s.push_back("a");
s.push_back("b");
s.push_back("c");
for_each( s.begin(), s.end(), [=](string str)
{
some_list.push_back(str);
}
);
for_each( some_list.begin(), some_list.end(), [](string ss) { cout << ss; } );
Although doing a simple loop is recommended :-)
Boost has the statechart library. http://www.boost.org/doc/libs/1_36_0/libs/statechart/doc/index.html
I can't speak to the use of it, though. Not used it myself (yet)
Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.
If we get the value as int
and we set it to String
, the error occurs. PFB my solution,
Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));
I would opt for AutoMapper, an open source and free mapping library which allows to map one type into another, based on conventions (i.e. map public properties with the same names and same/derived/convertible types, along with many other smart ones). Very easy to use, will let you achieve something like this:
Model model = Mapper.Map<Model>(dto);
Not sure about your specific requirements, but AutoMapper also supports custom value resolvers, which should help you writing a single, generic implementation of your particular mapper.
Use These two lines to your EditText
android:imeActionLabel="Done"
android:singleLine="true"
or you can achieve it Programmatically by this line.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
You can indeed match all those characters, but it's safer to escape the -
so that it is clear that it be taken literally.
If you are using a POSIX variant you can opt to use:
([[:alnum:]\-_]+)
But a since you are including the underscore I would simply use:
([\w\-]+)
(works in all variants)
I haven't seen this answer yet. Just use a regex; it removes all characters besides word characters (\w
) and number characters (\d
), followed by a whitespace character (\s
):
import re
s = "string. With. Punctuation?" # Sample string
out = re.sub(ur'[^\w\d\s]+', '', s)
You could use the CSS3 property to do it quite nicely. It resizes to ratio so no image distortion (although it does upscale small images). Just note, it's not implemented in all browsers yet.
background-size: 100%;
If you use ThreadPoolExecutor
, and you use submit() method, it will give you a Future
back. You can call cancel() on the returned Future to stop your Runnable
task.
I wasn't able to reproduce your problem in Google Chrome 4.0, IE8, or Firefox 3.5 using that code. The label and radio button stayed on the same line.
Try putting them both inside a <p>
tag, or set the radio button to be inline like The Elite Gentleman suggested.
I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.
Take a look (it works for me):
private void SerializeParams<T>(XDocument doc, List<T> paramList)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());
System.Xml.XmlWriter writer = doc.CreateWriter();
serializer.Serialize(writer, paramList);
writer.Close();
}
private List<T> DeserializeParams<T>(XDocument doc)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));
System.Xml.XmlReader reader = doc.CreateReader();
List<T> result = (List<T>)serializer.Deserialize(reader);
reader.Close();
return result;
}
So you can serialize whatever list you want! You don't need to specify the list type every time.
List<AssemblyBO> list = new List<AssemblyBO>();
list.Add(new AssemblyBO());
list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
XDocument doc = new XDocument();
SerializeParams<T>(doc, list);
List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
This will return an MD5 hash for a file on a remote computer:
Invoke-Command -ComputerName RemoteComputerName -ScriptBlock {
$fullPath = Resolve-Path 'c:\Program Files\Internet Explorer\iexplore.exe'
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$file = [System.IO.File]::OpenRead($fullPath)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($file))
$hash -replace "-", ""
$file.Dispose()
}
After the byte code (which is architecture neutral) has been generated by the Java compiler, the execution will be handled by the JVM (in Java). The byte code will be loaded in to JVM by the loader and then each byte instruction is interpreted.
When we need to call a method multiple times, we need to interpret the same code many times and this may take more time than is needed. So we have the JIT (just-in-time) compilers. When the byte has been is loaded in to JVM (its run time), the whole code will be compiled rather than interpreted, thus saving time.
JIT compilers works only during run time, so we do not have any binary output.
You pass them in just like you're thinking, and in your script, you get them from the array @ARGV
. Like so:
my $numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach my $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum]\n";
}
From here.
Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:
@AllArgsConstructor public class Parent { private String a; } public class Child extends Parent { private String b; @Builder public Child(String a, String b){ super(a); this.b = b; } }
As a result you can then use the generated builder like this:
Child.builder().a("testA").b("testB").build();
The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.
I also found this works nicely with Spring Data JPA.
numpy's genfromtxt or loadtxt is what I use:
import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')
This got me headed in the right direction and solved my problem.
DIV
elements can get focus if set the tabindex
attribute. Here is the working example.
#focus-example > .extra {_x000D_
display: none;_x000D_
}_x000D_
#focus-example:focus > .extra {_x000D_
display: block;_x000D_
}
_x000D_
<div id="focus-example" tabindex="0">_x000D_
<div>Focus me!</div>_x000D_
<div class="extra">Hooray!</div>_x000D_
</div>
_x000D_
For more information about focus
and blur
, you can check out this article.
Update:
And here is another example using focus
to create a menu
.
#toggleMenu:focus {_x000D_
outline: none;_x000D_
}_x000D_
button:focus + .menu {_x000D_
display: block;_x000D_
}_x000D_
.menu {_x000D_
display: none;_x000D_
}_x000D_
.menu:focus {_x000D_
display: none;_x000D_
}
_x000D_
<div id="toggleMenu" tabindex="0">_x000D_
<button type="button">Menu</button>_x000D_
<ul class="menu" tabindex="1">_x000D_
<li>Home</li>_x000D_
<li>About Me</li>_x000D_
<li>Contacts</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Try this :
ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it
Image newimg = image.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
imageIcon = new ImageIcon(newimg); // transform it back
(found it here)
Try sleep(int number_of_seconds)
I spent a good deal of time researching this situation for my own needs. This and several other SO threads helped me a great deal, so I wanted to share what I came up with.
While having access to the interpolated query string is a significant benefit while troubleshooting, we wanted to be able to maintain a log of only certain queries (therefore, using the database logs for this purpose was not ideal). We also wanted to be able to use the logs to recreate the condition of the tables at any given time, therefore, we needed to make certain the interpolated strings were escaped properly. Finally, we wanted to extend this functionality to our entire code base having to re-write as little of it as possible (deadlines, marketing, and such; you know how it is).
My solution was to extend the functionality of the default PDOStatement object to cache the parameterized values (or references), and when the statement is executed, use the functionality of the PDO object to properly escape the parameters when they are injected back in to the query string. We could then tie in to execute method of the statement object and log the actual query that was executed at that time (or at least as faithful of a reproduction as possible).
As I said, we didn't want to modify the entire code base to add this functionality, so we overwrite the default bindParam()
and bindValue()
methods of the PDOStatement object, do our caching of the bound data, then call parent::bindParam()
or parent::bindValue()
. This allowed our existing code base to continue to function as normal.
Finally, when the execute()
method is called, we perform our interpolation and provide the resultant string as a new property E_PDOStatement->fullQuery
. This can be output to view the query or, for example, written to a log file.
The extension, along with installation and configuration instructions, are available on github:
https://github.com/noahheck/E_PDOStatement
DISCLAIMER:
Obviously, as I mentioned, I wrote this extension. Because it was developed with help from many threads here, I wanted to post my solution here in case anyone else comes across these threads, just as I did.
I think style no. 111 (Japan) should work:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for any language and date format setting in SQL Server:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
Take a look on MDN
It will render html element using creating SVG images.
For Example:
There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>
HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
Canvas Element.
Here is Javascript Code to add HTML element to canvas.
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
'<foreignObject width="100%" height="100%">' +_x000D_
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
'<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
'</div>' +_x000D_
'</foreignObject>' +_x000D_
'</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
ctx.drawImage(img, 0, 0);_x000D_
DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
You should use g++
, not gcc
, to compile C++ programs.
For this particular program, I just typed
make avishay
and let make
figure out the rest. Gives your executable a decent name, too, instead of a.out
.
''' This code works for me, and is as simple as that.
Here I have taken the value of ip and I am trying to match it with regex.
ip="25.255.45.67"
op=re.match('(\d+).(\d+).(\d+).(\d+)',ip)
if ((int(op.group(1))<=255) and (int(op.group(2))<=255) and int(op.group(3))<=255) and (int(op.group(4))<=255)):
print("valid ip")
else:
print("Not valid")
Above condition checks if the value exceeds 255 for all the 4 octets then it is not a valid. But before applying the condition we have to convert them into integer since the value is in a string.
group(0) prints the matched output, Whereas group(1) prints the first matched value and here it is "25" and so on. '''
All DECLAREs need to be at the top. ie.
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//
div#wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
In Windows Vista or Windows 7, the manual file association editor has been removed.
The easiest way is to run Jarfix, a tiny but powerful freeware tool. Just run it and your Java apps is back... double-clickable again.
Never create classes. At least the OOP kind of classes in Python being discussed.
Consider this simplistic class:
class Person(object):
def __init__(self, id, name, city, account_balance):
self.id = id
self.name = name
self.city = city
self.account_balance = account_balance
def adjust_balance(self, offset):
self.account_balance += offset
if __name__ == "__main__":
p = Person(123, "bob", "boston", 100.0)
p.adjust_balance(50.0)
print("done!: {}".format(p.__dict__))
vs this namedtuple version:
from collections import namedtuple
Person = namedtuple("Person", ["id", "name", "city", "account_balance"])
def adjust_balance(person, offset):
return person._replace(account_balance=person.account_balance + offset)
if __name__ == "__main__":
p = Person(123, "bob", "boston", 100.0)
p = adjust_balance(p, 50.0)
print("done!: {}".format(p))
The namedtuple approach is better because:
inheritance
adds complexity, and hides complexity.I can't see a single advantage to using OOP classes. Obviously, if you are used to OOP, or you have to interface with code that requires classes like Django.
BTW, most other languages have some record type feature like namedtuples. Scala, for example, has case classes. This logic applies equally there.
If performance/memory usage is an issue then, this one only creates one (1) StringBuilder and one (1) new String of the same size as the Original string.
public static string ToUpperFirst(this string str) {
if( !string.IsNullOrEmpty( str ) ) {
StringBuilder sb = new StringBuilder(str);
sb[0] = char.ToUpper(sb[0]);
return sb.ToString();
} else return str;
}
Use white-space: nowrap;
[1] [2] or give that link more space by setting li
's width to greater values.
[1] § 3. White Space and Wrapping: the white-space property - W3 CSS Text Module Level 3
[2] white-space - CSS: Cascading Style Sheets | MDN
Use:
myarray.index "valuetoFind"
That will return you the index of the element you want or nil if your array doesn't contain the value.
This https://stackoverflow.com/a/13266763/1277458 works perfectly. But if you have 64-bit operation system use Framework64 instead of Framework in path:
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
To find distinct in field_1
in collection but we want some WHERE
condition too than we can do like following :
db.your_collection_name.distinct('field_1', {WHERE condition here and it should return a document})
So, find number distinct names
from a collection where age > 25 will be like :
db.your_collection_name.distinct('names', {'age': {"$gt": 25}})
Hope it helps!
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
ReSharper users can generate GetHashCode, Equals, and others with ReSharper -> Edit -> Generate Code -> Equality Members
.
// ReSharper's GetHashCode looks like this
public override int GetHashCode() {
unchecked {
int hashCode = Id;
hashCode = (hashCode * 397) ^ IntMember;
hashCode = (hashCode * 397) ^ OtherIntMember;
hashCode = (hashCode * 397) ^ (RefMember != null ? RefMember.GetHashCode() : 0);
// ...
return hashCode;
}
}
Use the force, read the source (excerpt from the Priority
and Level
class compiled, TRACE level was introduced in version 1.2.12):
public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT = 30000;
public final static int INFO_INT = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000;
public final static int ALL_INT = Integer.MIN_VALUE;
or the log4j API for the Level
class, which makes it quite clear.
When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger
object (based on configuration) and compares it with the LogEvent
's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent
's level is greater or equal to the Logger
's level, the LogEvent
is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.
This is not the solution to you, but if you want to restrict the function calls to some specific parameter types then you must use the PROATOR { The Python Function prototype validator }. you can refer the following link. https://github.com/mohit-thakur-721/proator
I had the same problem some time ago and was disappointed because I couldn't find any solution that suites my needs so I wrote my own class. Honestly, I did found some code back then, but even that wasn't what I was searching for so I adapted it and now I'm sharing it, just like the author of that piece of code did.
EDIT: This is the original (although slightly different) code: CircularArrayList for java
I don't have the link of the source because it was time ago, but here's the code:
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
public class CircularArrayList<E> extends AbstractList<E> implements RandomAccess {
private final int n; // buffer length
private final List<E> buf; // a List implementing RandomAccess
private int leader = 0;
private int size = 0;
public CircularArrayList(int capacity) {
n = capacity + 1;
buf = new ArrayList<E>(Collections.nCopies(n, (E) null));
}
public int capacity() {
return n - 1;
}
private int wrapIndex(int i) {
int m = i % n;
if (m < 0) { // modulus can be negative
m += n;
}
return m;
}
@Override
public int size() {
return this.size;
}
@Override
public E get(int i) {
if (i < 0 || i >= n-1) throw new IndexOutOfBoundsException();
if(i > size()) throw new NullPointerException("Index is greater than size.");
return buf.get(wrapIndex(leader + i));
}
@Override
public E set(int i, E e) {
if (i < 0 || i >= n-1) {
throw new IndexOutOfBoundsException();
}
if(i == size()) // assume leader's position as invalid (should use insert(e))
throw new IndexOutOfBoundsException("The size of the list is " + size() + " while the index was " + i
+". Please use insert(e) method to fill the list.");
return buf.set(wrapIndex(leader - size + i), e);
}
public void insert(E e)
{
int s = size();
buf.set(wrapIndex(leader), e);
leader = wrapIndex(++leader);
buf.set(leader, null);
if(s == n-1)
return; // we have replaced the eldest element.
this.size++;
}
@Override
public void clear()
{
int cnt = wrapIndex(leader-size());
for(; cnt != leader; cnt = wrapIndex(++cnt))
this.buf.set(cnt, null);
this.size = 0;
}
public E removeOldest() {
int i = wrapIndex(leader+1);
for(;;i = wrapIndex(++i)) {
if(buf.get(i) != null) break;
if(i == leader)
throw new IllegalStateException("Cannot remove element."
+ " CircularArrayList is empty.");
}
this.size--;
return buf.set(i, null);
}
@Override
public String toString()
{
int i = wrapIndex(leader - size());
StringBuilder str = new StringBuilder(size());
for(; i != leader; i = wrapIndex(++i)){
str.append(buf.get(i));
}
return str.toString();
}
public E getOldest(){
int i = wrapIndex(leader+1);
for(;;i = wrapIndex(++i)) {
if(buf.get(i) != null) break;
if(i == leader)
throw new IllegalStateException("Cannot remove element."
+ " CircularArrayList is empty.");
}
return buf.get(i);
}
public E getNewest(){
int i = wrapIndex(leader-1);
if(buf.get(i) == null)
throw new IndexOutOfBoundsException("Error while retrieving the newest element. The Circular Array list is empty.");
return buf.get(i);
}
}
Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.
Also, you may try the getUserMedia
method (supported by Opera 12)
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(textBox1.Text);
frm2.Show();
}
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
the crxml parser is a real easy to parser.
This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.
you can download this class at
http://freshmeat.net/projects/crxml
or from phpclasses.org
http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html
After Redis 2.6, the result of INFO command are splitted by sections. In the "keyspace" section, there are "keys" and "expired keys" fields to tell how many keys are there.
this fix does not require any path change
question is below is the error we get on running flutter doctor
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
? Android licenses not accepted. To resolve this, run: flutter doctor
--android-licenses
The solution lies in the problem itself ------> flutter doctor --android-licenses
So what this command means is there are certain licenses which Google want the developer to accept as part of app development
To dig deep just run flutter doctor --android-licenses
and keep typing y
to accept all the license agreements
once you have accepted all the agreements.
You'll see the following message on terminal "All SDK package licenses accepted"
now again re-run flutter doctor
command
[?] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
you will see the tick sign this time
Just download SQLEXPRWT_x64_ENU.exe from Microsoft Downloads - SQL Server® 2012 Express with SP1
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
Outside of your loop create an int:
int numberOfItemIds = 0;
for (int i = 0; i < key.length; i++) {
Then in the loop, increment it:
itemId = p.getItemId();
numberOfItemIds++;
You can also use the following vi command:
:%g/.*/j
Unlike the CMD.EXE CHDIR
or CD
command, the PowerShell Set-Location
cmdlet will change drive and directory, both. Get-Help Set-Location -Full
will get you more detailed information on Set-Location
, but the basic usage would be
PS C:\> Set-Location -Path Q:\MyDir
PS Q:\MyDir>
By default in PowerShell, CD
and CHDIR
are alias for Set-Location
.
(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)
I tried everything mentioned here and in other posts. Some of the solutions that people proffered were:
There were many, many more but the one that I found to work was as follows: Close the development environment. Delete the jars used by the project from my local Maven repository. Open the IDE. Build the project. Run the test.
After hours of beating my head against my keyboard and following suggested solutions, this one worked!
if you have the ability to install phpadmin there is a import section where you can import csv files to your database there is even a checkbox to set the header to the first line of the file contains the table column names (if this is unchecked, the first line will become part of the data
Solved this issue by removing transform: translateY(50%);
property.
A simple example using a regular expression which you could change to allow/disallow whatever you like.
$('input').on('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Assuming your script is something like the below snippet and named testargs.ps1
param ([string]$w)
Write-Output $w
You can call this at the commandline as:
PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.
If you are the only user of this repository, you can rewrite history using either git filter-branch
(as svick wrote), or git fast-export
/git fast-import
plus filter script (as described in article referenced in docgnome answer), or interactive rebase. But either of those would change revisions from first changed commit onwards; this means trouble for anybody that based his/her changes on your branch pre-rewrite.
RECOVERY
If other developers didn't based their work on pre-rewrite version, simplest solution would be to re-clone (clone again).
Alternatively they can try git rebase --pull
, which would fast-forward if there weren't any changes in their repository, or rebase their branch on top of re-written commits (we want to avoid merge, as it would keep pre-rewrite comits forever). All of this assuming that they do not have not comitted work; use git stash
to stash away changes otherwise.
If other developers use feature branches, and/or git pull --rebase
doesn't work e.g. because upstream is not set up, they have to rebase their work on top of post-rewrite commits. For example just after fetching new changes (git fetch
), for a master
branch based on / forked from origin/master
, one needs to run
$ git rebase --onto origin/master origin/master@{1} master
Here origin/master@{1}
is pre-rewrite state (before fetch), see gitrevisions.
Alternate solution would be to use refs/replace/ mechanism, available in Git since version 1.6.5. In this solution you provide replacements for commits that have wrong email; then anybody who fetches 'replace' refs (something like fetch = +refs/replace/*:refs/replace/*
refspec in appropriate place in their .git/config
) would get replacements transparently, and those who do not fetch those refs would see old commits.
The procedure goes something like this:
Find all commits with wrong email, for example using
$ git log [email protected] --all
For each wrong commit, create a replacement commit, and add it to object database
$ git cat-file -p <ID of wrong commit> |
sed -e 's/user@wrong\.email/[email protected]/g' > tmp.txt
$ git hash-object -t commit -w tmp.txt
<ID of corrected commit>
Now that you have corrected commit in object database, you have to tell git to automatically and transparently replace wrong commit by corrected one using git replace
command:
$ git replace <ID of wrong commit> <ID of corrected commit>
Finally, list all replacement to check if this procedure succeded
$ git replace -l
and check if replacements take place
$ git log [email protected] --all
You can of course automate this procedure... well, all except using git replace
which doesn't have (yet) batch mode, so you would have to use shell loop for that, or replace "by hand".
NOT TESTED! YMMV.
Note that you might encounter some rough corners when using refs/replace/
mechanism: it is new, and not yet very well tested.
If you have control over running the cscript executable then run the X:\windows\syswow64\cscript.exe
version which is the 32bit implementation.
dup2( STDIN_FILENO, newfd )
And read:
char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
perror( "dup2( )" );
exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
printf( "<%s>", reading );
memset( reading, '\0', 1025 );
}
if( r_control < 0 )
perror( "read( )" );
close( fdin );
But, I think that fcntl
can be a better solution
echo "salut" | code
An alternative solution would be to use the Url
helper object to set the href
attribute of an <a>
tag like:
<a href="@Url.Action("Details", "Product",new { id=item.ID }) )">Details</a>
There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).
This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.
There is no REVOKE ALL PRIVILEGES ON ALL VIEWS
, so I ended with:
do $$
DECLARE r record;
begin
for r in select * from pg_views where schemaname = 'myschem'
loop
execute 'revoke all on ' || quote_ident(r.schemaname) ||'.'|| quote_ident(r.viewname) || ' from "XUSER"';
end loop;
end $$;
and usual:
REVOKE ALL PRIVILEGES ON DATABASE mydb FROM "XUSER";
REVOKE ALL PRIVILEGES ON SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA myschem FROM "XUSER";
for the following to succeed:
drop role "XUSER";
You can use express-error-handler to use static html pages for error handling and to avoid defining a view handler.
The error was probably caused by a 404, maybe a missing favicon (apparent if you had included the previous console message). The 'view handler' of 'html' doesn't seem to be valid in 4.x express.
Regardless of the cause, you can avoid defining a (valid) view handler as long as you modify additional elements of your configuration.
Your options are to fix this problem are:
http://expressjs.com/en/api.html#res.render
Using render without a filepath automatically invokes a view handler as with the following two lines from your configuration:
res.render('404', { url: req.url });
and:
res.render('500);
Make sure you install express-error-handler with:
npm install --save express-error-handler
Then import it in your app.js
var ErrorHandler = require('express-error-handler');
Then change your error handling to use:
// define below all other routes
var errorHandler = ErrorHandler({
static: {
'404': 'error.html' // put this file in your Public folder
'500': 'error.html' // ditto
});
// any unresolved requests will 404
app.use(function(req,res,next) {
var err = new Error('Not Found');
err.status(404);
next(err);
}
app.use(errorHandler);
I have written a simple utility function.
public static String convert24HourTimeTo12Hour(String timeStr) {
try {
DateFormat inFormat = new SimpleDateFormat( "HH:mm:ss");
DateFormat outFormat = new SimpleDateFormat( "hh:mm a");
Date date = inFormat.parse(timeStr);
return outFormat.format(date);
}catch (Exception e){}
return "";
}
The code you listed kind of looks like a Lehmer RNG. If this is the case, then 2147483647
is the largest 32-bit signed integer, 2147483647
is the largest 32-bit prime, and 48271
is a full-period multiplier that is used to generate the numbers.
If this is true, you could modify RandomNumberGenerator
to take in an extra parameter seed
, and then set this.seed
to seed
; but you'd have to be careful to make sure the seed would result in a good distribution of random numbers (Lehmer can be weird like that) -- but most seeds will be fine.
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
according to this snippet i use this code and it's working fine:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace CompressString
{
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string CompressString(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <returns></returns>
public static string DecompressString(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
}
Check following to help the understand the concept of CTE recursion
DECLARE
@startDate DATETIME,
@endDate DATETIME
SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'
; WITH CTE AS (
SELECT
YEAR(@startDate) AS 'yr',
MONTH(@startDate) AS 'mm',
DATENAME(mm, @startDate) AS 'mon',
DATEPART(d,@startDate) AS 'dd',
@startDate 'new_date'
UNION ALL
SELECT
YEAR(new_date) AS 'yr',
MONTH(new_date) AS 'mm',
DATENAME(mm, new_date) AS 'mon',
DATEPART(d,@startDate) AS 'dd',
DATEADD(d,1,new_date) 'new_date'
FROM CTE
WHERE new_date < @endDate
)
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)
How about get_the_category?
You can then do
$category = get_the_category();
$firstCategory = $category[0]->cat_name;
You can use parcelable for object passing which is more efficient than Serializable .
Kindly refer the link which i am share contains complete parcelable sample. Click download ParcelableSample.zip
Using $emit and $broadcast, (as mentioned by walv in the comments above)
To fire an event upwards (from child to parent)
$scope.$emit('myTestEvent', 'Data to send');
To fire an event downwards (from parent to child)
$scope.$broadcast('myTestEvent', {
someProp: 'Sending you some data'
});
and finally to listen
$scope.$on('myTestEvent', function (event, data) {
console.log(data);
});
For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Enjoy :)
Example using react-router v4, redux-thunk and react-router-redux(5.0.0-alpha.6) package.
When user uses search feature, I want him to be able to send url link for same query to a colleague.
import { push } from 'react-router-redux';
import qs from 'query-string';
export const search = () => (dispatch) => {
const query = { firstName: 'John', lastName: 'Doe' };
//API call to retrieve records
//...
const searchString = qs.stringify(query);
dispatch(push({
search: searchString
}))
}
This is the easiest way :
step 1) install Spring Tool Suite (STS) for eclipse (version 3.7.0RELEASE or above) To do this you can go to Help >> eclipse market place , then type Spring Tool suite in search box.
step 2) now go to file >> new >> spring project as shown in the image below
step 3)now choose the template as "spring MVC Project" and give a name to your project on the top as shown below ( I named it 'SpringProject')
step 4)now give a base package name like this
and that is . The project will be created in a few minutes and Now you can right click on it and run on server.
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
there should has a concurrent implemention of List interface supporting such operation.
try java.util.concurrent.CopyOnWriteArrayList.class
I have found another solution
<style type="text/css">
.container {
width:600px; //set how much you want
overflow: hidden;
position: relative;
}
.containerSecond{
position: absolute;
top:0px;
left:-500%;
width:1100%;
}
.content{
width: 800px; //your content size
margin:0 auto;
}
</style>
and in body
<div class="container">
<div class="containerSecond">
<div class="content"></div>
</div>
</div>
This will center your content div whenever your container is bigger or smaller. In this case your content should be bigger than 1100% of container to not be centered, but in that case you can make with of containerSecond bigger, and it will work
Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.
Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r
to restore it.
DateTime.now.strftime("%Q")
Example usage:
>> DateTime.now.strftime("%Q")
=> "1541433332357"
>> DateTime.now.strftime("%Q").to_i
=> 1541433332357
I found out that my back-up project worked well if I precompile without bundle update
. Maybe something went wrong with gem updated but I don't know which gem has an error.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.