I found this page which tells you how to import a PFX to JKS (Java Key Store):
keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME
You are looking for -H
option in gnu grep.
find . -name '*bills*' -exec grep -H "put" {} \;
-H, --with-filename
Print the filename for each match.
You can get the view Back if you put an ID to your Layout.
<RelativeLayout
android:id="@+id/my_relative_layout_id"
And call it from findViewById ...
Use the below for both Exception type and Exception text
import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'")+"-"+(str(sys.exc_info()[1])))
if you want only exception type: Use -->
import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'"))
If you want to view all the commits that changed a file, in all the branches, use this:
git log --follow --all <filepath>
$ split -l 100 input_file output_file
where -l
is the number of lines in each files. This will create:
[HttpPost] // it use when you write logic on button click event
public ActionResult DemoInsert(EmployeeModel emp)
{
Employee emptbl = new Employee(); // make object of table
emptbl.EmpName = emp.EmpName;
emptbl.EmpAddress = emp.EmpAddress; // add if any field you want insert
dbc.Employees.Add(emptbl); // pass the table object
dbc.SaveChanges();
return View();
}
final is a variable declare with key word final
, example:
final double pi = 3.14 ;
it remains final
through out the program.
effectively final : any local variable or parameter that is assigned a value only once right now(or updated only once). It may not remain effectively final through out the program. so this means that effectively final variable might loose its effectively final property after immediately the time it gets assigned/updated at least one more assignment. example:
class EffectivelyFinal {
public static void main(String[] args) {
calculate(124,53);
}
public static void calculate( int operand1, int operand2){
int rem = 0; // operand1, operand2 and rem are effectively final here
rem = operand1%2 // rem lost its effectively final property here because it gets its second assignment
// operand1, operand2 are still effectively final here
class operators{
void setNum(){
operand1 = operand2%2; // operand1 lost its effectively final property here because it gets its second assignment
}
int add(){
return rem + operand2; // does not compile because rem is not effectively final
}
int multiply(){
return rem * operand1; // does not compile because both rem and operand1 are not effectively final
}
}
}
}
A quick way to add response buffering in .NET Core 3.1 is
app.Use((context, next) =>
{
context.Request.EnableBuffering();
return next();
});
in Startup.cs. I found this also guarantees that buffering will be enabled before the stream has been read, which was a problem for .Net Core 3.1 with some of the other middleware/authorization filter answers I've seen.
Then you can read your request body via HttpContext.Request.Body
in your handler as several others have suggested.
Also worth considering is that EnableBuffering
has overloads that allow you to limit how much it will buffer in memory before it uses a temporary file, and also an overall limit to you buffer. NB if a request exceeds this limit an exception will be thrown and the request will never reach your handler.
under etc/apache2/apache2.conf
, you can find one or more blocks that describe the server directories and permissions
As an example, this is the default configuration
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
you can replicate this but change the directory path /var/www/
with the new directory.
Finally, you need to restart the apache server, you can do that from a terminal with the command: sudo service apache2 restart
This is rather old question but this might be of some help for future reference. Delete node_modules folder and run npm install again. Worked for me.
We want to find something and then stop the inner iteration. I use a flag system.
for l in f:
flag = True
for e in r:
if flag==False:continue
if somecondition:
do_something()
flag=False
Following can also be done. If you want to append prepend icon. This will be helpful.
<?php $form = ActiveForm::begin();
echo $form->field($model, 'field')->begin();
echo Html::activeLabel($model, 'field', ["class"=>"control-label col-md-4"]); ?>
<div class="col-md-5">
<?php echo Html::activeDropDownList($model, 'field', $array_list, ['class'=>'form-control']); ?>
<p><i><small>Please select field</small></i>.</p>
<?php echo Html::error($model, 'field', ['class'=>'help-block']); ?>
</div>
<?php echo $form->field($model, 'field')->end();
ActiveForm::end();?>
Save this xml and add as a background for the linear layout....
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
Hope this helps! :)
Optimize your images ... Dont use images larger than 100KB ... Image loading takes too much CPU and cause your app hangs .
git show --stat origin/branch_name
This will give you a list of the files that have been added or modified under this branch.
It took me a bit of scouting around to suss this out, but I've settled on this cross-browser implementation:
HTML
<div class="video" style="display: none">
<div class="mask"></div>
<a href="#" class="close-btn"><span class="fa fa-times"></span></a>
<div class="overlay">
<iframe id="player" width="100%" height="70%" src="//www.youtube.com/embed/Xp697DqsbUU" frameborder="0" allowfullscreen></iframe>
</div>
</div>
jQuery
$('.launch-video').click(function() {
$('.video').show();
$("#player").attr('src','//www.youtube.com/embed/Xp697DqsbUU');
});
$('.close-btn').click(function() {
$('.video').hide();
$("#player").attr('src','');
});
What it essentially does is open my lightbox and populate my src attribute, and on close, just remove the src value (then re-populates it on open).
You may use this to access a specific folder and get particular image
public void Retrieve(String path, String Name)
{
File imageFile = new File(path+Name);
if(imageFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
myImage = (ImageView) findViewById(R.id.savedImage);
myImage.setImageBitmap(myBitmap);
Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
}
}
And then you can call it by
Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
On the realisation that you're unfamiliar with colspan
, I presumed you're also unfamiliar with rowspan
, so I thought I'd throw that in for free.
One important point to note, when using rowspan
: the following tr
elements must contain fewer td
elements, because of the cells using rowspan
in the previous row (or previous rows).
table {_x000D_
border: 1px solid #000;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th colspan="2">Column one and two</th>_x000D_
<th>Column three</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td rowspan="2" colspan="2">A large cell</td>_x000D_
<td>a smaller cell</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<!-- note that this row only has _one_ td, since the preceding row_x000D_
takes up some of this row -->_x000D_
<td>Another small cell</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
The technique that worked for me in my case, after reading these answers to no avail, was simply to comment out all of my contract, and uncomment bits until it doesn't work anymore, in a binary search fashion. That narrows down the offending bit of code.
Then you just have to guess what's wrong with that code.
Some error feedback in the tool would have helped, of course.
I am writing a web service contract. I had a placeholder enum with no members. That's OK. But if I use it in a property of another class, and re-use the contract dll on the client, the codegen explodes with no error message. Running svcutil.exe didn't help, it just failed to output a cs file without mentioning why.
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.
import React from 'react';
import withRouter from 'react-router-dom';
const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)
export withRouter(MyComponent);
use the following code:
$homepage = file_get_contents("https://www.google.com",false,
stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
]
])
);
echo $homepage;
I'm using Android Studio (JetBrains IntelliJ IDEA) on Mac OS and my problem was that ^M started to show up in some files in my pull request on GitHub. What worked for me was changing line separator for a file.
Open the desired file in the editor go to File go to Line Separators then choose the best option for you (for me it was LF - Unix and OS X(\n) )
According to the next article this problem is a result of confused line endings between operating systems: http://jonathonstaff.com/blog/issues-with-line-endings/
And more information you can find here: https://www.jetbrains.com/help/idea/configuring-line-separators.html#d84378e48
I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py
This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.
Today 2020.02.27 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
d1==d2
(D) and d1===d2
(E) are fastest for all browsersgetTime
(A) is faster than valueOf
(B) (both are medium fast)In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE
function A(d1,d2) {_x000D_
return d1.getTime() == d2.getTime();_x000D_
}_x000D_
_x000D_
function B(d1,d2) {_x000D_
return d1.valueOf() == d2.valueOf();_x000D_
}_x000D_
_x000D_
function C(d1,d2) {_x000D_
return Number(d1) == Number(d2);_x000D_
}_x000D_
_x000D_
function D(d1,d2) {_x000D_
return d1 == d2;_x000D_
}_x000D_
_x000D_
function E(d1,d2) {_x000D_
return d1 === d2;_x000D_
}_x000D_
_x000D_
function F(d1,d2) {_x000D_
return (!(d1>d2 || d2>d1));_x000D_
}_x000D_
_x000D_
function G(d1,d2) {_x000D_
return d1*1 == d2*1;_x000D_
}_x000D_
_x000D_
function H(d1,d2) {_x000D_
return +d1 == +d2;_x000D_
}_x000D_
_x000D_
function I(d1,d2) {_x000D_
return !(+d1 - +d2);_x000D_
}_x000D_
_x000D_
function J(d1,d2) {_x000D_
return !(d1 - d2);_x000D_
}_x000D_
_x000D_
function K(d1,d2) {_x000D_
return d1 - d2 == 0;_x000D_
}_x000D_
_x000D_
function L(d1,d2) {_x000D_
return !((d1>d2)-(d1<d2));_x000D_
}_x000D_
_x000D_
function M(d1,d2) {_x000D_
return d1.getFullYear() === d2.getFullYear()_x000D_
&& d1.getDate() === d2.getDate()_x000D_
&& d1.getMonth() === d2.getMonth();_x000D_
}_x000D_
_x000D_
function N(d1,d2) {_x000D_
return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );_x000D_
}_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
let past= new Date('2002-12-24'); // past_x000D_
let now= new Date('2020-02-26'); // now_x000D_
_x000D_
console.log('Code d1>d2 d1<d2 d1=d2')_x000D_
var log = (l,f) => console.log(`${l} ${f(now,past)} ${f(past,now)} ${f(now,now)}`);_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);
_x000D_
p {color: red}
_x000D_
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
_x000D_
Results for chrome
Thanks to the previous commenters I found all the following worked for me:
Either adding an onclick stub to the element
onclick="void(0);"
or user a cursor pointer style
style="cursor:pointer;"
or as in my existing code my jquery code needed tap added
$(document).on('click tap','.ciAddLike',function(event)
{
alert('like added!'); // stopped working in ios safari until tap added
});
I am adding a cross-reference back to the Apple Docs for those interested. See Apple Docs:Making Events Clickable
(I'm not sure exactly when my hybrid app stopped processing clicks but I seem to remember they worked iOS 7 and earlier.)
This is what I like to do:
$files = array_values(array_filter(scandir($path), function($file) use ($path) {
return !is_dir($path . '/' . $file);
}));
foreach($files as $file){
echo $file;
}
For example $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");
1.) if $result is only one row.
$response = mysql_fetch_array($result);
echo json_encode($response);
2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.
$rows = array();
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["USERID"]; //a column name (ex.ID) used to get a value of the single row at at time
$rows[$id] = $r; //save the fetched row and add it to the array.
}
}
echo json_encode($rows);
I had a similar situation, i wanted to wait for ajax requests so that the loading panel would have disappeared, I have inspected the html before and after the requests, found that there is a div for the ajax loading panel, the dix is displayed during the ajax request, and hidden after the request ends. I have created a function to wait for the panel to be displayed, then wait for it to be hidden
public void WaitForModalPanel()
{
string element_xpath = ".//*[@id='ajaxLoadingModalPanelContainer' and not(contains(@style,'display: none'))]";
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 2, 0));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(element_xpath)));
element_xpath = ".//*[@id='ajaxLoadingModalPanelContainer' and contains(@style,'DISPLAY: none')]";
wait.Until(ExpectedConditions.ElementExists(By.XPath(element_xpath)));
}
Check this for more details
Use single quote with single char as:
char ch = 'a';
here 'a'
is a char constant and is equal to the ASCII
value of char a.
Use double quote with strings as:
char str[] = "foo";
here "foo"
is a string literal.
Its okay to use "a"
but its not okay to use 'foo'
let newQueue = DispatchQueue(label: "newname")
newQueue.sync {
// your code
}
Actually I did it by uncommenting extension=php_curl.dll
in the xampp\apache\bin\php.ini file.
This error can be caused by an unclosed set of brackets.
int main {
doSomething {}
doSomething else {
}
Not so easy to spot, even in this 4 line example.
This error, in a 150 line main function, caused the bewildering error: "static declaration of ‘savePair’ follows non-static declaration". There was nothing wrong with my definition of function savePair, it was that unclosed bracket.
Have your thread notify some other thread when it’s finished. This way you’ll always know exactly what’s going on.
This type of data is efficiently pulled from a Trie-like data structure. It also allows for fast sorting. The memory efficiency might not be that great though.
A traditional trie stores each letter of a word as a node in the tree. But in your case your "alphabet" is different. You are storing strings instead of characters.
it might look something like this:
root: Root
/|\
/ | \
/ | \
fruit: Banana Apple Strawberry
/ | | \
/ | | \
color: Blue Yellow Green Blue
/ | | \
/ | | \
end: 24 100 12 0
see this link: trie in python
I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.
#include <string>
#include <vector>
...
string rawInput;
vector<String> numbers;
while( getline( cin, rawInput, ' ' ) )
{
numbers.push_back(rawInput);
}
So say the input looks like this:
Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7
You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.
Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.
while(!numbers.empty())
{
string temp = numbers.pop_back();//removes the last element from the string
num = atoi( temp.c_str() ); //re-used your 'num' variable from your code
...//do stuff
}
Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:
#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)
Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/
Edit: I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].
#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
bool isNum = true;
for(int i = 0; i < rawInput.length() && isNum; ++i)
{
isNum = isdigit( rawInput[i]);
}
if(isNum)
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
else
cout << rawInput << " is not a number!" << endl;
}
The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.
Dynamic URL with Get and Post method in Retrofit (MVVM)
Retrofit Service interface:
public interface NetworkAPIServices {
@POST()
Observable<JsonElement> executXYZServiceAPI(@Url String url,@Body AuthTokenRequestModel param);
@GET
Observable<JsonElement> executeInserInfo(@Url String url);
MVVM service class:
public Observable<JsonElement> executXYZServiceAPI(ModelObject object) {
return networkAPIServices.authenticateAPI("url",
object);
}
public Observable<JsonElement> executeInserInfo(String ID) {
return networkAPIServices.getBank(DynamicAPIPath.mergeUrlPath("url"+ID)));
}
and Retrofit Client class
@Provides
@Singleton
@Inject
@Named("provideRetrofit2")
Retrofit provideRetrofit(@Named("provideRetrofit2") Gson gson, @Named("provideRetrofit2") OkHttpClient okHttpClient) {
builder = new Retrofit.Builder();
if (BaseApplication.getInstance().getApplicationMode() == ApplicationMode.DEVELOPMENT) {
builder.baseUrl(NetworkURLs.BASE_URL_UAT);
} else {
builder.baseUrl(NetworkURLs.BASE_URL_PRODUCTION);
}
builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
builder.client(okHttpClient);
builder.addConverterFactory(GsonConverterFactory.create(gson));
return builder.build();
}
for example This is url : https://gethelp.wildapricot.com/en/articles/549-changing-your
baseURL : https://gethelp.wildapricot.com
Remaining @Url: /en/articles/549-changing-your (which is you pass in retro service class)
If you want to add a click listener in chrome console, use this
document.querySelectorAll("label")[6].parentElement.onclick = () => {console.log('label clicked');}
This language feature is convenient in this situation.
public String getName() {
return (String) memberHashMap.get("Name");
}
If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.
Here is the official answer of IntelliJ IDEA 2018.3 Help. I tried and It worked.
To build a JAR file from a module;
On the main menu, choose Build | Build Artifact.
From the drop-down list, select the desired artifact of the type JAR. The list shows all the artifacts configured for the current project. To have all the configured artifacts built, choose the Build all artifacts option.
Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).
The function that works best for me is Excel.WorksheetFunction.Sum()
Example:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.
The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
I had the same issue with
C:\Program Files\Java\jdk1.8.0_51\bin\keytool
but the same keystore file worked fine with
"C:\Program Files\Java\jre1.8.0_201\bin\keytool"
I knw it is an old thread but hav lost lot of hours figuring this out... :D
Set a far future absolute time:
setcookie("CookieName", "CookieValue", 2147483647);
It is better to use an absolute time than calculating it relative to the present as recommended in the accepted answer.
The maximum value compatible with 32 bits systems is:
2147483647 = 2^31 = ~year 2038
Too late for you, but for anyone else with the same question...
//a[contains(text(), 'programming')]/@href
Of course, 'programming' can be any text fragment.
You can use like the following
string result = null;
object value = cmd.ExecuteScalar();
if (value != null)
{
result = value.ToString();
}
conn.Close();
return result;
(Using as an example your first link)
You want to duplicate the behavior of an old HP calculator, there are two options:
You write new program that draws the calculator's display and keys, and when the user clicks on the keys, your programs does what the old calculator did. This is a Simulator
You get a dump of the calculator's firmware, then write a program that loads the firmware and interprets it the same way the microprocessor in the calculator did. This is an Emulator
The Simulator tries to duplicate the behavior of the device.
The Emulator tries to duplicate the inner workings of the device.
The middle one writes to the pipeline. Write-Host
and Out-Host
writes to the console. 'echo' is an alias for Write-Output
which writes to the pipeline as well. The best way to write to the console would be using the Write-Host
cmdlet.
When an object is written to the pipeline it can be consumed by other commands in the chain. For example:
"hello world" | Do-Something
but this won't work since Write-Host
writes to the console, not to the pipeline (Do-Something will not get the string):
Write-Host "hello world" | Do-Something
To further expand on @neontapir's solution, here's a more generic solution that can apply to HttpRequestMessage or HttpResponseMessage equally and doesn't require hand coded expressions or functions.
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
public static class HttpResponseMessageExtensions
{
public static T GetFirstHeaderValueOrDefault<T>(
this HttpResponseMessage response,
string headerKey)
{
var toReturn = default(T);
IEnumerable<string> headerValues;
if (response.Content.Headers.TryGetValues(headerKey, out headerValues))
{
var valueString = headerValues.FirstOrDefault();
if (valueString != null)
{
return (T)Convert.ChangeType(valueString, typeof(T));
}
}
return toReturn;
}
}
Sample usage:
var myValue = response.GetFirstHeaderValueOrDefault<int>("MyValue");
if protobuf is installed then import it like this
pip install protobuf
import google.protobuf
Ctrl + Shift + O (<-- an 'O' not a zero)
Note: This shortcut also removes unused imports.
In Addition to the accepted answer: My scipt gave me an error
File "c:\Python23\lib\urllib2.py", line 580, in proxy_open
if '@' in host:
TypeError: iterable argument required
Solution was to add http:// in front of the proxy string:
proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
old question that I stumbled into that I believe deserves an update... You can infact execute javascript from the URL, and you can get creative about it too. I recently made a members only area that I wanted to remind someone what their password was, so I was looking for a non-local alert...of course you can embed an alert into the page itself, but then its public. the difference here is I can create a link and slip some JS into the href so clicking on the link will generate the alert.
here is what I mean >>
<a href="javascript:alert('the secret is to ask.');window.location.replace('http://google.com');">You can have anything</a>
and so upon clicking the link, the user is given an alert with the info, then they are taken to the new page.
obviously you could also write an onClick, but the href works just fine when you slip it through the URL, just remember to prepend it with "javascript:"
*works in chrome, didnt check anything else.
I know this is in the above answers, but my point is that I think all you need is
new Date(collectionDate);
if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").
INSERT INTO TARGET_TABLE SELECT * FROM SOURCE_TABLE;
EDIT: or if the tables have different structures you can also:
INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;
EDIT: to constrain this..
INSERT INTO TARGET_TABLE (`col1_`,`col2_`) SELECT `col1`,`col2` FROM SOURCE_TABLE WHERE `foo`=1
For Mac users, edit the /etc/hosts
file. You have to use sudo vi /etc/hosts
if its read-only. After authorization, the oauth server sends the callback URL, and since that callback URL is rendered on your local browser, the local DNS setting will work:
127.0.0.1 mylocal.com
Consider the tricks that <a href> knows by default but javascript linking won't do for you. On a decent website, anything that wants to behave as a link should implement these features one way or another. Namely:
Now if you don't want to simulate all that behaviour, I suggest to use <a href> and style it like a button, since the button itself is roughly a shape and a hover effect. I think if it's not semantically important to only have "the button and nothing else", <a href> is the way of the samurai. And if you worry about semantics and readability, you can also replace the button element when your document is ready(). It's clear and safe.
$$
is an alias in Bash to the current script PID. See differences between $$
and $BASHPID
here, and right above that the additional variable $BASH_SUBSHELL
which contains the nesting level.USE style="max-width:90%;"
<select name=countries style="max-width:90%;">
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
This works fine with hostname, reverse IP (for internal networks) and IP.
function pingAddress($ip) {
$ping = exec("ping -n 2 $ip", $output, $status);
if (strpos($output[2], 'unreachable') !== FALSE) {
return '<span style="color:#f00;">OFFLINE</span>';
} else {
return '<span style="color:green;">ONLINE</span>';
}
}
echo pingAddress($ip);
How about a Java 8 implementation? (null can be replaced by your default Enum)
public static RandomEnum getEnum(String value) {
return Arrays.stream(RandomEnum.values()).filter(m -> m.value.equals(value)).findAny().orElse(null);
}
Or you could use:
...findAny().orElseThrow(NotFoundException::new);
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
Another option, in addition to using OPENQUERY and xp_cmdshell, is to use SQLCLR (SQL Server's "CLR Integration" feature). Not only is the SQLCLR option more secure than those other two methods, but there is also the potential benefit of being able to call the stored procedure in the current session such that it would have access to any session-based objects or settings, such as:
This can be achieved by using "context connection = true;" as the ConnectionString. Just keep in mind that all other restrictions placed on T-SQL User-Defined Functions will be enforced (i.e. cannot have any side-effects).
If you use a regular connection (i.e. not using the context connection), then it will operate as an independent call, just like it does when using the OPENQUERY and xp_cmdshell methods.
HOWEVER, please keep in mind that if you will be using a function that calls a stored procedure (regardless of which of the 3 noted methods you use) in a statement that affects more than 1 row, then the behavior cannot be expected to run once per row. As @MartinSmith mentioned in a comment on @MatBailie's answer, the Query Optimizer does not guarantee either the timing or number of executions of functions. But if you are using it in a SET @Variable = function();
statement or SELECT * FROM function();
query, then it should be ok.
An example of using a .NET / C# SQLCLR user-defined function to execute a stored procedure is shown in the following article (which I wrote):
Stairway to SQLCLR Level 2: Sample Stored Procedure and Function
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
In the new Jenkins 2.0 pipeline (previously named the Workflow Plugin), this is done differently for:
Here I am specifically referring to the Multibranch Pipeline version 2.9.
Main repository
This is the repository that contains your Jenkinsfile
.
In the Configure screen for your pipeline project, enter your repository name, etc.
Do not use Additional Behaviors > Check out to a sub-directory. This will put your Jenkinsfile
in the sub-directory where Jenkins cannot find it.
In Jenkinsfile
, check out the main repository in the subdirectory using dir()
:
dir('subDir') {
checkout scm
}
Additional repositories
If you want to check out more repositories, use the Pipeline Syntax generator to automatically generate a Groovy code snippet.
In the Configure screen for your pipeline project:
env.BRANCH_NAME
contains the branch name of the main repository.Jenkinsfile
.The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
Swift 3 - Uses only textures and SKSpriteNode, doesn't require UIView
import Foundation
import SpriteKit
class GradientSpriteNode : SKSpriteNode
{
convenience init(size: CGSize, colors: [UIColor], locations: [CGFloat])
{
let texture = GradientSpriteNode.texture(size: size, colors: colors, locations: locations)
self.init(texture: texture, color:SKColor.clear, size: texture.size())
}
private override init(texture: SKTexture!, color: SKColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private static func texture(size: CGSize, colors: [UIColor], locations: [CGFloat]) -> SKTexture
{
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors.map{$0.cgColor} as CFArray, locations: locations)!
context.drawLinearGradient(gradient, start: CGPoint(x: size.width / 2, y: 0), end: CGPoint(x: size.width / 2, y: size.height), options: CGGradientDrawingOptions())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return SKTexture(image: image!)
}
}
Usage:
let gradient = GradientSpriteNode(
size: CGSize(width: 100, height: 100),
colors: [UIColor.red, UIColor.blue],
locations: [0.0, 1.0])
addChild(gradient)
Make sure you have installed npm i @types/node
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon's code.
$(document).ready(function(){
$('.slider').slick({
autoplay:true,
arrows: true,
prevArrow:"<button type='button' class='slick-prev pull-left'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
nextArrow:"<button type='button' class='slick-next pull-right'><i class='fa fa-angle-right' aria-hidden='true'></i></button>"
});
});
Old question I know, but this is now possible using the css property table-layout: fixed
on the table tag. Answer below from this question CSS percentage width and text-overflow in a table cell
This is easily done by using table-layout: fixed
, but a little tricky because not many people know about this CSS property.
table {
width: 100%;
table-layout: fixed;
}
See it in action at the updated fiddle here: http://jsfiddle.net/Fm5bM/4/
A compiler consists of two major blocks: the 'front end' and the 'back end'. The front end of a compiler analyzes the source code and builds some form of a 'intermediary representation' of said source code which is much easier to analyze by a machine algorithm than is the source code (i.e. whereas the source code e.g. C++ is designed to help the human programmer to write code, the intermediary form is designed to help simplify the algorithm that analyzes said intermediary form easier). The back end of a compiler takes the intermediary form and then converts it to a 'target language'.
Now, the target language for general-use compilers are assembler languages for various processors, but there's nothing to prohibit a compiler back end to produce code in some other language, for as long as said target language is (at least) as flexible as a general CPU assembler.
Now, as you can probably imagine, C is definitely as flexible as a CPU's assembler, such that a C++ to C compiler is really no problem to implement from a technical pov.
So you have: C++ ---frontEnd---> someIntermediaryForm ---backEnd---> C
You may want to check these guys out: http://www.edg.com/index.php?location=c_frontend (the above link is just informative for what can be done, they license their front ends for tens of thousands of dollars)
PS As far as i know, there is no such a C++ to C compiler by GNU, and this totally beats me (if i'm right about this). Because the C language is fairly small and it's internal mechanisms are fairly rudimentary, a C compiler requires something like one man-year work (i can tell you this first hand cause i wrote such a compiler myself may years ago, and it produces a [virtual] stack machine intermediary code), and being able to have a maintained, up-to-date C++ compiler while only having to write a C compiler once would be a great thing to have...
You can use the bit_length() function to convert numbers to their two's complement:
def twos_complement(j):
return j-(1<<(j.bit_length()))
In [1]: twos_complement(0b111111111111)
Out[1]: -1
To replace one or more white space characters by a single blank you should use {2,}
instead of *
, otherwise you would insert
a blank between all non-blank characters.
REGEXP_REPLACE( my_value, '[[:space:]]{2,}', ' ' )
you can write the function in a separate file (say common-functions.php) and include it wherever needed.
function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}
You can include common-functions.php in another file as below.
include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);
You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.
Check the file which you have selected in the request.
For me i was getting the error because the file was not present in the system, as i have imported the request from some other machine.
I recommend using the emulator by Genymotion instead of Google's emulators. It launches way faster and responds almost in real-time. It also supports Google Play Services and therefore Google Maps.
Give it a try! Here is a blog post which helps you setting up the emulator.
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
Simplest way is definitely to enter the following command in the terminal:
sudo gem update --system
You can add the flag --no-document
if you do not want to download the documentation. Here is sample output after running the command:
sudo gem update --system
Password:
Updating rubygems-update
Fetching: rubygems-update-2.6.8.gem (100%)
Successfully installed rubygems-update-2.6.8
Parsing documentation for rubygems-update-2.6.8
Installing ri documentation for rubygems-update-2.6.8
Installing darkfish documentation for rubygems-update-2.6.8
Installing RubyGems 2.6.8
RubyGems 2.6.8 installed
Parsing documentation for rubygems-2.6.8
Installing ri documentation for rubygems-2.6.8
------------------------------------------------------------------------------
RubyGems installed the following executables:
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/gem
Ruby Interactive (ri) documentation was installed. ri is kind of like man
pages for ruby libraries. You may access it like this:
ri Classname
ri Classname.class_method
ri Classname#instance_method
textBox1.Text = "Line1\r\r\Line2";
Solved the problem.
This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
An alternative solution is to store the keys in a separate Collection:
'Initialise these somewhere.
Dim Keys As Collection, Values As Collection
'Add types for K and V as necessary.
Sub Add(K, V)
Keys.Add K
Values.Add V, K
End Sub
You can maintain a separate sort order for the keys and the values, which can be useful sometimes.
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
Create a new SSH key in your terminal/command line.
ssh-keygen -t rsa -C “your-email-address”
The following will then show:
Generating public/private rsa key pair. Enter file in which to save the key (/home/your_username/.ssh/id_rsa):
Copy and paste the path followed by an identifiable name for the file:
/home/your_username/.ssh/id_rsa_personal
4) It will then ask you for the following:
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
5) You can now type in the following command to see all the SSH keys you have on your local machine:
ls -al ~/.ssh
You should be able to see your new SSH key file. As you can see in my one I have both id_rsa_test and id_rsa_personal.pub.
drwx------ 2 gmadmin gmadmin 4096 Nov 16 22:20 .
drwxr-xr-x 42 gmadmin gmadmin 4096 Nov 16 21:03 ..
-rw------- 1 gmadmin gmadmin 1766 Nov 16 22:20 id_rsa_personal
-rw-r--r-- 1 gmadmin gmadmin 414 Nov 16 22:20 id_rsa_personal.pub
-rw-r--r-- 1 gmadmin gmadmin 444 Nov 6 11:32 known_hosts
6) Next you need to copy the SSH key which is stored in id_rsa_personal.pub file. You can open this in text editor of your choice. I am currently using atom so I opened the file using the following command:
atom ~/.ssh/id_rsa_personal.pub
You will then get something similar to this:
ssh-rsa AAB3HKJLKC1yc2EAAAADAQABAAABAQCgU5+ELtwsKkmcoeF3hNd7d6CjW+dWut83R/Dc01E/YzLc5ZFri18doOwuQoeTPpmIRVDGuQQsZshjDrTkFy8rwKWMlXl7va5olnGICcpg4qydEtsW+MELDmayW1HHsi2xHMMGHlNv
7) Copy this and navigate to your GitHub account ? Settings ? SSH and GPG keys 8) Click on New SSH key. Copy the key, give it a title and add it. 9) Add key from terminal
ssh-add ~/.ssh/id_rsa_personal
Enter passphrase for /home/your_username/.ssh/id_rsa_personal:
10) Configure user and password.
git config --global user.name "gitusername"
git config --global user.email "gitemail"
11) We are ready to commit and push now.
git init
git add .
git commit
git push
My 2¢! Really, part of the reason I'm throwing this up here, despite the long list of answers, is to provide a little more all in one
type solution and get some feed back in the future on how to expand it to include more real types
.
With the following solution, as aforementioned, I combined a couple of solutions found here, as well as incorporate a fix for returning a value of jQuery on jQuery defined object if available. I also append the method to the native Object prototype. I know that is often taboo, as it could interfere with other such extensions, but I leave that to user beware
. If you don't like this way of doing it, simply copy the base function anywhere you like and replace all variables of this
with an argument parameter to pass in (such as arguments[0]).
;(function() { // Object.realType
function realType(toLower) {
var r = typeof this;
try {
if (window.hasOwnProperty('jQuery') && this.constructor && this.constructor == jQuery) r = 'jQuery';
else r = this.constructor && this.constructor.name ? this.constructor.name : Object.prototype.toString.call(this).slice(8, -1);
}
catch(e) { if (this['toString']) r = this.toString().slice(8, -1); }
return !toLower ? r : r.toLowerCase();
}
Object['defineProperty'] && !Object.prototype.hasOwnProperty('realType')
? Object.defineProperty(Object.prototype, 'realType', { value: realType }) : Object.prototype['realType'] = realType;
})();
Then simply use with ease, like so:
obj.realType() // would return 'Object'
obj.realType(true) // would return 'object'
Note: There is 1 argument passable. If is bool of
true
, then the return will always be in lowercase.
More Examples:
true.realType(); // "Boolean"
var a = 4; a.realType(); // "Number"
$('div:first').realType(); // "jQuery"
document.createElement('div').realType() // "HTMLDivElement"
If you have anything to add that maybe helpful, such as defining when an object was created with another library (Moo, Proto, Yui, Dojo, etc...) please feel free to comment or edit this and keep it going to be more accurate and precise. OR roll on over to the GitHub I made for it and let me know. You'll also find a quick link to a cdn min file there.
Applying the Observer Pattern with delegates and events in c# is named "Event Pattern" according to MSDN which is a slight variation.
In this Article you will find well structured examples of how to apply the pattern in c# both the classic way and using delegates and events.
Exploring the Observer Design Pattern
public class Stock
{
//declare a delegate for the event
public delegate void AskPriceChangedHandler(object sender,
AskPriceChangedEventArgs e);
//declare the event using the delegate
public event AskPriceChangedHandler AskPriceChanged;
//instance variable for ask price
object _askPrice;
//property for ask price
public object AskPrice
{
set
{
//set the instance variable
_askPrice = value;
//fire the event
OnAskPriceChanged();
}
}//AskPrice property
//method to fire event delegate with proper name
protected void OnAskPriceChanged()
{
AskPriceChanged(this, new AskPriceChangedEventArgs(_askPrice));
}//AskPriceChanged
}//Stock class
//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs : EventArgs
{
//instance variable to store the ask price
private object _askPrice;
//constructor that sets askprice
public AskPriceChangedEventArgs(object askPrice) { _askPrice = askPrice; }
//public property for the ask price
public object AskPrice { get { return _askPrice; } }
}//AskPriceChangedEventArgs
You can use either the language construct isset
, or the function array_key_exists
.
isset
should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL
.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset
:
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
boolean true
While the second one will get you (the element exists, but is null) :
boolean false
And the last one will get you (the element doesn't exist) :
boolean false
On the other hand, using array_key_exists
like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'd get those outputs :
boolean true
boolean true
boolean false
Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.
For situations such as yours, I generally use isset
, considering I'm never in the second case... But choosing which one to use is now up to you ;-)
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}
The below code will convert the current date into the timestamp.
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours
inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
On your servlet simply override the service method of your servlet so that you can add headers for all your http methods (POST, GET, DELETE, PUT, etc...).
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if(("http://www.example.com").equals(req.getHeader("origin"))){
res.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
res.setHeader("Access-Control-Allow-Headers", "Authorization");
}
super.service(req, res);
}
In addition to the other answers, this error can result if there's an inconsistency in an order by clause. For instance:
select
substr(year_month, 1, 4)
,count(*) as tot
from
schema.tbl
group by
substr(year_month, 1, 4)
order by
year_month
No need to find
. If you are just looking for a pattern within a specific directory, this should suffice:
grep -hn FOO /your/path/*.bar
Where -h
is the parameter to hide the filename, as from man grep
:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
Note that you were using
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
# To support matches from the beginning, not any matches:
items = ['a', 'ab', 'abc', 'bac']
prefix = 'ab'
filter(lambda x: x.startswith(prefix), items)
int main()
{
long mylong = 123456789;
string mystring;
stringstream mystream;
mystream << mylong;
mystring = mystream.str();
cout << mystring << "\n";
return 0;
}
Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.
I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:
class InputAssigningMetaclass(type):
def __new__(cls, name, bases, attrs):
cls.input = get_input(name)
return super(MyType, cls).__new__(cls, name, bases, newattrs)
class MyBaseFoo(object):
__metaclass__ = InputAssigningMetaclass
class foo(MyBaseFoo):
# etc, no need to create 'input'
class foo2(MyBaseFoo):
# etc, no need to create 'input'
The construction like this: $('[data-XXX=111]')
isn't working in Safari 8.0.
If you set data attribute this way: $('div').data('XXX', 111)
, it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111)
.
I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of myform
:
$("#myform > input[type=reset]").trigger('click');
This for me had the correct outcome on resetting the form, oh and dont forget the
event.preventDefault();
to stop the form submitting in browser, like I did :).
Regards
Jacko
"." | "!" | "~" | "*" | "'" | "(" | ")"
are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.
You can use os.walk()
to recursively iterate through a directory and all its subdirectories:
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith((".html", ".htm")):
# whatever
To build a list of these names, you can use a list comprehension:
htmlfiles = [os.path.join(root, name)
for root, dirs, files in os.walk(path)
for name in files
if name.endswith((".html", ".htm"))]
Check this example of post the array of different types
function PostArray() {
var myObj = [
{ 'fstName': 'name 1', 'lastName': 'last name 1', 'age': 32 }
, { 'fstName': 'name 2', 'lastName': 'last name 1', 'age': 33 }
];
var postData = JSON.stringify({ lst: myObj });
console.log(postData);
$.ajax({
type: "POST",
url: urlWebMethods + "/getNames",
data: postData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (msg) {
alert(msg.d);
}
});
}
If using a WebMethod in C# you can retrieve the data like this
[WebMethod]
public static string getNames(IEnumerable<object> lst)
{
string names = "";
try
{
foreach (object item in lst)
{
Type myType = item.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
if(prop.Name == "Values")
{
Dictionary<string, object> dic = item as Dictionary<string, object>;
names += dic["fstName"];
}
}
}
}
catch (Exception ex)
{
names = "-1";
}
return names;
}
Example in POST an array of objects with $.ajax to C# WebMethod
Passing data to view is simple as passing object to method. Take a look at Controller.View Method
protected internal ViewResult View(
Object model
)
Something like this
//controller
List<MyObject> list = new List<MyObject>();
return View(list);
//view
@model List<MyObject>
// and property Model is type of List<MyObject>
@foreach(var item in Model)
{
<span>@item.Name</span>
}
Hibernate caches objects from the session. If object is accessed and modified by more than 1 user then org.hibernate.StaleStateException
may be be thrown. It may be solved with merge/refresh entity method before saving or using lock. More info: http://java-fp.blogspot.lt/2011/09/orghibernatestalestateexception-batch.html
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
isn't the code:
var text = $('#listItem').clone().children().remove().end().text();
just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:
(function ($) {
function elementText(el, separator) {
var textContents = [];
for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
if (chld.nodeType == 3) {
textContents.push(chld.nodeValue);
}
}
return textContents.join(separator);
}
$.fn.textNotChild = function(elementSeparator, nodeSeparator) {
if (arguments.length<2){nodeSeparator="";}
if (arguments.length<1){elementSeparator="";}
return $.map(this, function(el){
return elementText(el,nodeSeparator);
}).join(elementSeparator);
}
} (jQuery));
to call:
var text = $('#listItem').textNotChild();
the arguments are in case a different scenario is encountered, such as
<li>some text<a>more text</a>again more</li>
<li>second text<a>more text</a>again more</li>
var text = $("li").textNotChild(".....","<break>");
text will have value:
some text<break>again more.....second text<break>again more
Improved One-Liner answer: If you are looking for a boolean return value, we can do it better by adding isPresent:
return dataSource.getParkingLots().stream().filter(parkingLot -> Objects.equals(parkingLot.getId(), id)).findFirst().isPresent();
It's better to use JSON.parse(yourUnescapedJson);
You can do
var modal = {} as IModal
I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive
This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.
Based on the the source code of setTextSize
:
public void setTextSize(int unit, float size) {
Context c = getContext();
Resources r;
if (c == null)
r = Resources.getSystem();
else
r = c.getResources();
setRawTextSize(TypedValue.applyDimension(
unit, size, r.getDisplayMetrics()));
}
I build this function for calulating any demension to pixels:
int getPixels(int unit, float size) {
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
return (int)TypedValue.applyDimension(unit, size, metrics);
}
Where unit is something like TypedValue.COMPLEX_UNIT_SP
.
You have an option to define collation order at the time of defining your table. If you define a case-sensitive order, your LIKE
operator will behave in a case-sensitive way; if you define a case-insensitive collation order, the LIKE
operator will ignore character case as well:
CREATE TABLE Test (
CI_Str VARCHAR(15) COLLATE Latin1_General_CI_AS -- Case-insensitive
, CS_Str VARCHAR(15) COLLATE Latin1_General_CS_AS -- Case-sensitive
);
Here is a quick demo on sqlfiddle showing the results of collation order on searches with LIKE
.
Here it worked on Mac OS X.
It includes the example of a BSD date, how to increment and decrement the date also:
for ((i=28; i>=6 ; i--));
do
dat=`date -v-${i}d -j "+%Y%m%d"`
echo $dat
done
For more recent settings, see Eclipse Galileo 3.5 settings above.
The best JVM setting always, in my opinion, includes the latest JDK you can find (so for now, jdk1.6.0_b07 up to b16, except b14 and b15)
Even with those pretty low memory settings, I can run large java projects (along with a web server) on my old (2002) desktop with 2Go RAM.
-showlocation
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
-vm
jdk1.6.0_10\jre\bin\client\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms128m
-Xmx384m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CompileThreshold=5
-Dcom.sun.management.jmxremote
See GKelly's SO answer and Piotr Gabryanczyk's blog entry for more details about the new options.
You can also consider launching:
C:\[jdk1.6.0_0x path]\bin\jconsole.exe
As said in a previous question about memory consumption.
to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.
delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);
it does not require much configurations just go to advanced system settings copy the path where you have installed your node and just create an environment variable and check with node -v command in your prompt!
Console.Read()
Console.ReadLine()
Console.ReadKey()
I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here:
Using UTF8 with Python MySQLdb
Edit: Quote from the above URL to satisfy the request in the first comment...
"UnicodeEncodeError:'latin-1' codec can't encode character ..."
This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:
db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')
"db" is the result of
MySQLdb.connect()
, and "dbc" is the result ofdb.cursor()
.
try using the css pseudoclass :focus
input[type="button"], input[type="button"]:focus {
/* your style goes here */
}
edit as for links and onclick events use (you shouldn’t use inline javascript eventhandlers, but for the sake of simplicity i will use them here):
<a href="some/page.php" title="perform some js action" onclick="callFunction(this.href);return false;">watch and learn</a>
with this.href you can even access the target of the link in your function. return false
will just prevent browsers from following the link when clicked.
if javascript is disabled the link will work as a normal link and just load some/page.php
—if you want your link to be dead when js is disabled use href="#"
Ruby 2.4.0 is released, and it has an Enumerable#sum method. So you can do
array.sum
Examples from the docs:
{ 1 => 10, 2 => 20 }.sum {|k, v| k * v } #=> 50
(1..10).sum #=> 55
(1..10).sum {|v| v * 2 } #=> 110
you may change your loop condition according to following code, when length of l is smaller than buffer size it means that it reached end of file
while (True):
print "Receiving..."
l = c.recv(1024)
f.write(l)
if len(l) < 1024:
break
Just came across the same issue today...
In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:
list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)
While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.
Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("@Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
The traditional way to do this is to use the Flags
attribute on an enum
:
[Flags]
public enum Names
{
None = 0,
Susan = 1,
Bob = 2,
Karen = 4
}
Then you'd check for a particular name as follows:
Names names = Names.Susan | Names.Bob;
// evaluates to true
bool susanIsIncluded = (names & Names.Susan) != Names.None;
// evaluates to false
bool karenIsIncluded = (names & Names.Karen) != Names.None;
Logical bitwise combinations can be tough to remember, so I make life easier on myself with a FlagsHelper
class*:
// The casts to object in the below code are an unfortunate necessity due to
// C#'s restriction against a where T : Enum constraint. (There are ways around
// this, but they're outside the scope of this simple illustration.)
public static class FlagsHelper
{
public static bool IsSet<T>(T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
return (flagsValue & flagValue) != 0;
}
public static void Set<T>(ref T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue | flagValue);
}
public static void Unset<T>(ref T flags, T flag) where T : struct
{
int flagsValue = (int)(object)flags;
int flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue & (~flagValue));
}
}
This would allow me to rewrite the above code as:
Names names = Names.Susan | Names.Bob;
bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);
bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);
Note I could also add Karen
to the set by doing this:
FlagsHelper.Set(ref names, Names.Karen);
And I could remove Susan
in a similar way:
FlagsHelper.Unset(ref names, Names.Susan);
*As Porges pointed out, an equivalent of the IsSet
method above already exists in .NET 4.0: Enum.HasFlag
. The Set
and Unset
methods don't appear to have equivalents, though; so I'd still say this class has some merit.
Note: Using enums is just the conventional way of tackling this problem. You can totally translate all of the above code to use ints instead and it'll work just as well.
find the installed node version.
$ node --version
or
$ node -v
And if you want more information about installed node(i.e. node version,v8 version,platform,env variables info etc.)
then just do this.
$ node
> process
process {
title: 'node',
version: 'v6.6.0',
moduleLoadList:
[ 'Binding contextify',
'Binding natives',
'NativeModule events',
'NativeModule util',
'Binding uv',
'NativeModule buffer',
'Binding buffer',
'Binding util',
...
where The process object is a global that provides information about, and control over, the current Node.js process.
I have been working on to write a custom module in Drupal 7 and got the same error:
Notice: Trying to get property of non-object
My code is something like this:
function example_node_access($node, $op, $account) {
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes to it.','error');
return NODE_ACCESS_DENY;
}
}
Solution:
I just added a condition if (is_object($sqlResult))
, and everything went fine.
Here is my final code:
function mediaten_node_access($node, $op, $account) {
if (is_object($node)){
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes.','error');
return NODE_ACCESS_DENY;
}
}
}
You are modifying the list book_shop.values()[i]
, which is not getting updated in the dictionary. Whenever you call the values()
method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.
Cloud watch also allows you to create metrics for your S3 bucket. It shows you metrics by the size and object count. Services> Management Tools> Cloud watch. Pick the region where your S3 bucket is and the size and object count metrics would be among those available metrics.
I had to remove .idea and target folders and after reading all comments this worked for me:
git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'
and then push to master
I am not certain if this meets your requirements, given I think you are interested in making the file readable by people, but if that's not a primary concern, just pickle
it.
To save it:
import pickle
my_data = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
output = open('data.pkl', 'wb')
pickle.dump(my_data, output)
output.close()
To read it back:
import pprint, pickle
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
pkl_file.close()
One more solution by combining 2 top answers:
"To clear the last used search pattern:
nnoremap <F3> :let @/ = ""<CR>
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
Had this issue too. Invalidating Caches/Restart did the trick for me. Please upvote so the the IntelliJ folks take this more seriously. This gives the IDE a terrible UI/UX experience.
In the HKEY_USERS\oneyouwanttoknow\
you can look at \Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
and it will reveal their profile paths. c:\users\whothisis\Desktop
, etc.
After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.
The important parts for me was:
This is the solution i came up with. And hope it can be of use to others as well.
Change the width of .file_input_textbox to change the width of the textbox.
Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...
To test this solution, make a new html file and paste the content into it.
<html>
<head>
<style type="text/css">
.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button {width: 80px;position:absolute;top:0px;
border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
<input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
<div class="file_input_div">
<input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
<input type="file" class="file_input_hidden"
onchange="javascript: document.getElementById('fileName').value = this.value"
onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>
Update Oct 2020:
So if you are on this page scratching your head why my favicon is not working , then read along. I tried all the things (which I supposedly thought I was doing right) yet favicon was not showing up on browser tabs.
Here is one line simple cracker code that worked flawlessly:
<link rel="icon" href="https://abcde.neocities.org/bla123.jpg" size="16x16" type="image/jpg">
Notes:
I tested it on Firefox, Chrome, Edge, and opera. OS: Win 10, Mac OSX, ios and Android .Also I did not experience any cashing issues, worked pretty much as soon as I refreshed the page.
Simply use the checked
property of the checkAll
and use use prop() instead of attr for checked property
$('#checkAll').click(function () {
$('input:checkbox').prop('checked', this.checked);
});
Use prop() instead of attr() for properties like checked
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method
You have same id for checkboxes and its should be unique. You better use some class with the dependent checkboxes so that it does not include the checkboxes you do not want. As $('input:checkbox')
will select all checkboxes on the page. If your page is extended with new checkboxes then they will also get selected/un-selected. Which might not be the intended behaviour.
$('#checkAll').click(function () {
$(':checkbox.checkItem').prop('checked', this.checked);
});
I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
IF (@c IS NULL) RETURN NULL;_x000D_
DECLARE @WHITESPACE NCHAR(31);_x000D_
SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
-- Check tiny strings (NULL, 0 or 1 chars)_x000D_
IF @TEXT IS NULL RETURN N'';_x000D_
DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
IF @TEXTLENGTH < 2 BEGIN_x000D_
IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
RETURN @TEXT;_x000D_
END_x000D_
-- Check whether we have to LTRIM/RTRIM_x000D_
DECLARE @SKIPSTART INT;_x000D_
SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
DECLARE @SKIPEND INT;_x000D_
SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
DECLARE @INDEX INT;_x000D_
IF (@SKIPSTART = 1) BEGIN_x000D_
IF (@SKIPEND = 1) BEGIN_x000D_
-- FULLTRIM_x000D_
-- Determine start white-space length_x000D_
SELECT @INDEX = 2;_x000D_
WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise assign index as @SKIPSTART_x000D_
SELECT @SKIPSTART = @INDEX;_x000D_
-- Increase character index_x000D_
SELECT @INDEX = (@INDEX + 1);_x000D_
END_x000D_
-- Return '' if the whole string is white-space_x000D_
IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
-- Determine end white-space length_x000D_
SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
WHILE (@INDEX > 1) BEGIN _x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise increase @SKIPEND_x000D_
SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
-- Decrease character index_x000D_
SELECT @INDEX = (@INDEX - 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
END _x000D_
-- LTRIM_x000D_
-- Determine start white-space length_x000D_
SELECT @INDEX = 2;_x000D_
WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise assign index as @SKIPSTART_x000D_
SELECT @SKIPSTART = @INDEX;_x000D_
-- Increase character index_x000D_
SELECT @INDEX = (@INDEX + 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
END ELSE BEGIN_x000D_
-- RTRIM_x000D_
IF (@SKIPEND = 1) BEGIN_x000D_
-- Determine end white-space length_x000D_
SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
WHILE (@INDEX > 1) BEGIN _x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise increase @SKIPEND_x000D_
SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
-- Decrease character index_x000D_
SELECT @INDEX = (@INDEX - 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
END _x000D_
END_x000D_
-- NO TRIM_x000D_
RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
Have you tried mode 'a+'?
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell()
will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
To understand the various transactional settings and behaviours adopted for Transaction management, such as REQUIRED
, ISOLATION
etc. you'll have to understand the basics of transaction management itself.
Read Trasaction management for more on explanation.
Put this in main.py:
#!/usr/bin/python
import yoursubfile
Put this in yoursubfile.py
#!/usr/bin/python
print("hello")
Run it:
python main.py
It prints:
hello
Thus main.py
runs yoursubfile.py
There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
SOLUTIONS
g++
. So install g++
first and then recreate your project. This worked for me.CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++
Note the path to g++
depends on OS. I have used my fedora path obtained using which g++
Although with different code, I experienced the same problem as the OP, because I originally used
fm.beginTransaction()
.add(R.id.fragment_container_main, fragment)
.addToBackStack(null)
.commit();
instead of
fm.beginTransaction()
.replace(R.id.fragment_container_main, fragment)
.addToBackStack(null)
.commit();
With "replace" the first fragment gets recreated when you return from the second fragment and therefore onResume() is also called.
You were almost done without any changes besides how you spyOn
.
When you use the spy, you have two options: spyOn
the App.prototype
, or component component.instance()
.
const spy = jest.spyOn(Class.prototype, "method")
The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.
const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);
The App.prototype
bit on the first line there are what you needed to make things work. A JavaScript class
doesn't have any of its methods until you instantiate it with new MyClass()
, or you dip into the MyClass.prototype
. For your particular question, you just needed to spy on the App.prototype
method myClickFn
.
jest.spyOn(component.instance(), "method")
const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");
This method requires a shallow/render/mount
instance of a React.Component
to be available. Essentially spyOn
is just looking for something to hijack and shove into a jest.fn()
. It could be:
A plain object
:
const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");
A class
:
class Foo {
bar() {}
}
const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance
const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.
Or a React.Component instance
:
const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");
Or a React.Component.prototype
:
/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.
I've used and seen both methods. When I have a beforeEach()
or beforeAll()
block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.
EDIT:
If you want to check the side effects of your myClickFn
you can just invoke it in a separate test.
const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/
EDIT:
Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn()
as opposed to jest.spyOn
, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.
function Component({ myClickFn, items }) {
const handleClick = (id) => {
return () => myClickFn(id);
};
return (<>
{items.map(({id, name}) => (
<div key={id} onClick={handleClick(id)}>{name}</div>
))}
</>);
}
const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);
The percentage setting does not take into account the original image size. From w3schools :
In HTML 4.01, the width could be defined in pixels or in % of the containing element. In HTML5, the value must be in pixels.
Also, good practice advice from the same source :
Tip: Downsizing a large image with the height and width attributes forces a user to download the large image (even if it looks small on the page). To avoid this, rescale the image with a program before using it on a page.
It turns out the original poster's server (blueHost) has a FAQ concerning this very question.
Article 206.
This is because our servers require you (or your script) to use a properly formatted, valid From: field in the email's header. If the From: field is not formatted correctly, empty or the email address does not exist in the cPanel, the From: address will be changed to username@box###.bluehost.com
.
You must change the script you are using to correctly use a valid From: header.
Examples of headers that should work would be:
From: [email protected]
From: "user" <[email protected]>
Examples of headers that will NOT work:
From: "[email protected]"
From: user @ domain.com
From: [email protected] <[email protected]>
Our servers will not accept the name for the email address and the email address to be the same. It will not accept a double declaration of the email address.
For scripts such as Joomla and Wordpress, you will need to follow their documentation for formatting the from fields properly. Wordpress will require the Mail From plugin.
Note: The email address you use must be a valid created account in the cPanel.
On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:
if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
Yes, you can read the spec a hundred times, and combine different bits and pieces until you have an interpretation that feels right – but that's exactly what the browser vendors did and that's why we're in the situation we are today.
In essence, when you apply a width of 100% to an element it should extend to 100% of it's parent's width, if that parent is a block element. You can't center it anymore with margin: 0 auto;
then since it already takes up 100% of the available width.
To center anything with margin: 0 auto;
you need to define an explicit width. To center an inline element, you can use text-align: center;
on the parent element, although this could have unwanted side-effects if the parent has other children.
Here is the Javascript Code: (index.php)
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/sqldb.php", true);
xhttp.send("screensize=",screen.width,screen.height);
</script>
Here is the PHP Code: (sqldb.php)
$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));
I hope that you know how to get the $userid from the Session, and for that you need an Database with the Table called users, and an Table inside users called screen ;=) Regards KSP
You could use robocopy:
robocopy "$(TargetPath)" "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules" /E
None of these wonderful answers worked for me on a fresh install of Ubuntu. Instead, a clue from this answer did the trick for me.
I had to allow "simple" password store by setting this empty in ~/.subversion/config
:
password-stores =
There was no existing setting, so being empty is significant.
This was in addition to:
store-passwords = yes
in ~/.subversion/servers
.
For ENTER key, why not use (keyup.enter)
:
@Component({
selector: 'key-up3',
template: `
<input #box (keyup.enter)="values=box.value">
<p>{{values}}</p>
`
})
export class KeyUpComponent_v3 {
values = '';
}
1) If file /var/spool/cron/crontabs/root
edit via SFTP client - need service cron restart
.
Reload service not work.
2) If edit file /var/spool/cron/crontabs/root
via console linux (nano, mc) - restart NOT need.
3) If edit cron via crontab -e
- restart NOT need.
Using pyquaternion is extremely simple; to install it (while still in python), run in your console:
import pip;
pip.main(['install','pyquaternion'])
Once installed:
from pyquaternion import Quaternion
v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian
rotated_v = Quaternion(axis=axis,angle=theta).rotate(v)
Find elements:
var elements = document.getElementsByClassName('widget hover');
Since elements
is a live
array and reflects all dom changes you can remove all hover
classes with a simple while loop:
while(elements.length > 0){
elements[0].classList.remove('hover');
}
From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):
child::*
selects all element children of the context node
child::text()
selects all text node children of the context node
child::node()
selects all the children of the context node, whatever their node type
So I guess your answer is:
$doc/PRESENTEDIN/X/child::node()
And if you want a flatten array of all nested nodes:
$doc/PRESENTEDIN/X/descendant::node()
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Using dt.weekday_name
is deprecated since pandas 0.23.0
, instead, use dt.day_name()
:
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['my_dates'].dt.day_name()
0 Thursday
1 Friday
2 Saturday
Name: my_dates, dtype: object
To remove migration (if you already migrated the migration)
rake db:migrate:down VERSION="20130417185845" #Your migration version
To remove Model
rails d model name #name => Your model name
You can use query parameters for filtering and path parameters for grouping. The following link has good info on this When to use pathParams or QueryParams
Create a mock with Mockito (in "Java statements" context):
${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);
And in "Java type members":
${:import(org.mockito.Mock)}@Mock
${Type} ${mockName};
Mock a void method to throw an exception:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});
Mock a void method to do something:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object arg1 = invocation.getArguments()[0];
return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});
Verify mocked method called exactly once:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});
Verify mocked method is never invoked:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});
New linked list using Google Guava (and similar for hashset and hashmap):
${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();
Also I use a huge template that generates a Test class. Here is a shortened fragment of it that everyone interested should customize:
package ${enclosing_package};
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;
// TODO autogenerated test stub
@RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {
@InjectMocks
protected ${testedType} ${testedInstance};
${cursor}
@Mock
protected Logger logger;
@Before
public void setup() throws Exception {
}
@Test
public void shouldXXX() throws Exception {
// given
// when
// TODO autogenerated method stub
// then
fail("Not implemented.");
}
}
// Here goes mockito+junit cheetsheet
The same idea as Tatu(thanks I'll need it soon in our project), but with a regular expression.
Which may be quicker for large dataset.
<html>
<head>
<title>excelToTable</title>
<script src="../libs/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<textarea>a1 a2 a3
b1 b2 b3</textarea>
<div></div>
<input type="button" onclick="convert()" value="convert"/>
<script>
function convert(){
var xl = $('textarea').val();
$('div').html(
'<table><tr><td>' +
xl.replace(/\n+$/i, '').replace(/\n/g, '</tr><tr><td>').replace(/\t/g, '</td><td>') +
'</tr></table>'
)
}
</script>
</body>
</html>
Without actually seeing your data it is difficult to say how to find location of max and min in your particular case, but in general, you can search for the locations as follows. This is just a simple example below:
In [9]: a=np.array([5,1,2,3,10,4])
In [10]: np.where(a == a.min())
Out[10]: (array([1]),)
In [11]: np.where(a == a.max())
Out[11]: (array([4]),)
Alternatively, you can also do as follows:
In [19]: a=np.array([5,1,2,3,10,4])
In [20]: a.argmin()
Out[20]: 1
In [21]: a.argmax()
Out[21]: 4
In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:
function calculatePercent(amount, percent) {
const amountDecimals = getNumberOfDecimals(amount);
const percentDecimals = getNumberOfDecimals(percent);
const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`; // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}
function getNumberOfDecimals(number) {
const decimals = parseFloat(number).toString().split('.')[1];
if (decimals) {
return decimals.length;
}
return 0;
}
calculatePercent(20.05, 10); // 2.005
As you can see, I:
amount
and the percent
amount
and percent
to integers using exponential notationThe usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.
what about http://jsbin.com/esepal/2
$(document).bind("DOMSubtreeModified",function(){
console.log($('body').width() + ' x '+$('body').height());
})
This event has been deprecated in favor of the Mutation Observer API
Angular’s keyvalue
pipe can be used, but unfortunately it sorts by key. Maps already have an order and it would be great to be able to keep it!
We can define out own pipe mapkeyvalue
which preserves the order of items in the map:
import { Pipe, PipeTransform } from '@angular/core';
// Holds a weak reference to its key (here a map), so if it is no longer referenced its value can be garbage collected.
const cache = new WeakMap<ReadonlyMap<any, any>, Array<{ key: any; value: any }>>();
@Pipe({ name: 'mapkeyvalue', pure: true })
export class MapKeyValuePipe implements PipeTransform {
transform<K, V>(input: ReadonlyMap<K, V>): Iterable<{ key: K; value: V }> {
const existing = cache.get(input);
if (existing !== undefined) {
return existing;
}
const iterable = Array.from(input, ([key, value]) => ({ key, value }));
cache.set(input, iterable);
return iterable;
}
}
It can be used like so:
<mat-select>
<mat-option *ngFor="let choice of choicesMap | mapkeyvalue" [value]="choice.key">
{{ choice.value }}
</mat-option>
</mat-select>
(?<!1\.2\.3\.4).*Has exploded
You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:
grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log
Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4
. Hope that helps!
I found this question looking for a way to do the same thing for my Javascript tests, using Protractor (a javascript frontend to Selenium.)
My solution with protractor 1.2.0 and webdriver 2.1:
browser.actions()
.mouseMove(
element(by.css('.material-dialog-container'))
)
.click()
.perform();
This also accepts an offset (i'm using it to click above and left of an element:)
browser.actions()
.mouseMove(
element(by.css('.material-dialog-container'))
, -20, -20 // pixel offset from top left
)
.click()
.perform();
This confusing me a bit too.
The problem is on "path" attribute in your xml file.
From this document FileProvider 'path' is a subdirectory, but in another document (camera/photobasics) shown 'path' is full path.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
I just change this 'path' to full path and it just work.
If you want to use this in VBA:
For i = 1 To X
UserForm1.Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.
MainClass.java
public class MainClass {
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
String jsonStr = "{\r\n" + " \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf-
43d6-b598-7c0c550635bb\",\r\n"
+ " \"type\": \"getDashboard\",\r\n" + " \"data\": {\r\n"
+ " \"workstationUuid\": \"ddec1caa-a97f-4922-833f-
632da07ffc11\"\r\n" + " },\r\n"
+ " \"reply\": true\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
MyPojo details = mapper.readValue(jsonStr, MyPojo.class);
System.out.println("Value for getFirstName is: " + details.getId());
System.out.println("Value for getLastName is: " + details.getSocket());
System.out.println("Value for getChildren is: " +
details.getData().getWorkstationUuid());
System.out.println("Value for getChildren is: " + details.getReply());
}
MyPojo.java
public class MyPojo {
private String id;
private Data data;
private String reply;
private String socket;
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getReply() {
return reply;
}
public void setReply(String reply) {
this.reply = reply;
}
public String getSocket() {
return socket;
}
public void setSocket(String socket) {
this.socket = socket;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Data.java
public class Data {
private String workstationUuid;
public String getWorkstationUuid() {
return workstationUuid;
}
public void setWorkstationUuid(String workstationUuid) {
this.workstationUuid = workstationUuid;
}
}
RESULTS:
Value for getFirstName is: 2 Value for getLastName is: 0c317829-69bf-43d6-b598-7c0c550635bb Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11 Value for getChildren is: true
I have never had any luck with any scrollable content placed inside a stackpanel (anything derived from ScrollableContainer. The stackpanel has an odd layout mechanism that confuses child controls when the measure operation is completed and I found the vertical size ends up infinite, therefore not constrained - so it goes beyond the boundaries of the container and ends up clipped. The scrollbar doesn't show because the control thinks it has all the space in the world when it doesn't.
You should always place scrollable content inside a container that can resolve to a known height during its layout operation at runtime so that the scrollbars size appropriately. The parent container up in the visual tree must be able to resolve to an actual height, and this happens in the grid if you set the height of the RowDefinition o to auto or fixed.
This also happens in Silverlight.
-em-
Let video muted first to ensure autoplay in ios, then unmute it if you want.
<video autoplay loop muted playsinline>
<source src="video.mp4?123" type="video/mp4">
</video>
<script type="text/javascript">
$(function () {
if (!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
$("video").prop('muted', false);
}
});
</script>
I think;
while(msg->state != mExit)
{
switch(msg->state)
{
case MSGTYPE: // ...
break;
case DONE:
// ..
// ..
msg->state =mExit;
break;
}
}
if (msg->state ==mExit)
msg->state =DONE;
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
This is more of a maths problem than a java problem basically.
The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:
or in java:
int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;
jquery.ajax({
url: `//your api url`
type: "GET",
dataType: "json",
success: function(data) {
jQuery.each(data, function(index, value) {
console.log(data);
`All you API data is here`
}
}
});
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
My objective is to check if the 'onEditButtonClick' is getting invoked when the user clicks the edit button and not checking just the console.log being printed.
You will need to first set up the test using the Angular TestBed
. This way you can actually grab the button and click it. What you will do is configure a module, just like you would an @NgModule
, just for the testing environment
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
describe('', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ],
declarations: [ TestComponent ],
providers: [ ]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
}));
});
Then you need to spy on the onEditButtonClick
method, click the button, and check that the method was called
it('should', async(() => {
spyOn(component, 'onEditButtonClick');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.whenStable().then(() => {
expect(component.onEditButtonClick).toHaveBeenCalled();
});
}));
Here we need to run an async
test as the button click contains asynchronous event handling, and need to wait for the event to process by calling fixture.whenStable()
It is now preferred to use fakeAsync/tick
combo as opposed to the async/whenStable
combo. The latter should be used if there is an XHR call made, as fakeAsync
does not support it. So instead of the above code, refactored, it would look like
it('should', fakeAsync(() => {
spyOn(component, 'onEditButtonClick');
let button = fixture.debugElement.nativeElement.querySelector('button');
button.click();
tick();
expect(component.onEditButtonClick).toHaveBeenCalled();
}));
Don't forget to import fakeAsync
and tick
.
Your code should work perfectly, I use it the same way. Only make sure that if the click event is triggered from within a pop up screen like a bootstrap modal or something, the created element has to be within that modal otherwise it won't copy. You could always give the id of an element within that modal (as a second parameter) and retrieve it with getElementById, then append the newly created element to that one instead of the document. Something like this:
copyToClipboard = (text, elementId) => {
const textField = document.createElement('textarea');
textField.innerText = text;
const parentElement = document.getElementById(elementId);
parentElement.appendChild(textField);
textField.select();
document.execCommand('copy');
parentElement.removeChild(textField);
}
@Sydney Try putting wp_reset_query() before you call the loop. This will display the content of your page.
<?php
wp_reset_query(); // necessary to reset query
while ( have_posts() ) : the_post();
the_content();
endwhile; // End of the loop.
?>
EDIT: Try this if you have some other loops that you previously ran. Place wp_reset_query(); where you find it most suitable, but before you call this loop.
You can just use a UNIX pipe for this
brew deps [FORMULA] | xargs brew rm
I don't know what you are comparing to.
But a super simple way to have a border look inset when compared to other non-bordered items is to add a border: ?px solid transparent;
to whatever items do not have a border.
It will make the bordered item look inset.
Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
{"key1":"value1"}
Load Project:>Build, execution, Deployment:>(Check on)compiler Independent modules in parllel.
Using what others mentioned, I wanted this to be a quick & dandy function in my bash shell.
Create a file: ~/.functions
Add to it the contents:
getline() {
line=$1
sed $line'q;d' $2
}
Then add this to your ~/.bash_profile
:
source ~/.functions
Now when you open a new bash window, you can just call the function as so:
getline 441 myfile.txt
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified
it worked.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified(username)
user.markModified(password)
user.markModified(rights)
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
tell mongoose about the change with doc.markModified('pathToYourDate') before saving.
"ABCDEFG".chars.each do |char|
puts char
end
also
"ABCDEFG".each_char {|char| p char}
Ruby version >2.5.1
Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.
For OR, just have 2 cases without the break on the 1st. Eg:
case 'a':
case 'A':
// do stuff
break;
The "illegal instruction" message is simply telling you that your binaries contain instructions the version of the OS that you are attempting to run them under does not understand. I can't give you the precise meaning of 4
but I expect that is internal to Apple.
Otherwise take a look at these... they are a little old, but probably tell you what you need to know
How does 64 bit code work on OS-X 10.5?
what does macosx-version-min imply?
SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)
You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
With Symfony 4.2.7, I'm able to implement the following in my twig template, which displays the custom route name I defined in my controller(s).
In index.html.twig
<div class="col">
{% set current_path = app.request.get('_route') %}
{{ current_path }}
</div>
In my controller
...
class ArticleController extends AbstractController {
/**
* @Route("/", name="article_list")
* @Method({"GET"})
*/
public function index() {
...
}
...
}
The result prints out "article_list" to the desired page in my browser.
If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.
On the toolbar on the Test panel, set the test scope to "Line by line". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)
On the GREP panel, you can turn on the "line-based" and the "invert results" checkboxes to get a list of non-matching lines in the files you're grepping through.
Just do this:
git checkout master
Or, if you have changes that you want to keep, do this:
git checkout -b temp
git checkout -B master temp