If the window was shown with Window.ShowDialog()
:
The simplest solution that I know of is to set the IsCancel
property to true of the close Button
:
<Button Content="Close" IsCancel="True" />
No bindings needed, WPF will do that for you automatically!
This properties provide an easy way of saying these are the "OK" and "Cancel" buttons on a dialog. It also binds the ESC key to the button.
Reference: MSDN Button.IsCancel property.
You want:
insert into prices (group, id, price)
select
7, articleId, 1.50
from article where name like 'ABC%';
where you just hardcode the constant fields.
try
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
appLog.Source = "This Application's Name";
appLog.WriteEntry("An entry to the Application event log.");
Open Android Studio, Go to Tools then Android and then SDK, uncheck NDK If you do not need this, and restart android studio.
Simplay you can place HTML select attribute to option
a
like shown below
Define the attributes like selected="selected"
<select>
<option selected="selected">a</option>
<option>b</option>
<option>c</option>
</select>
simply change <div>
to <tbody>
<table id="authenticationSetting" style="display: none">
<tbody id="authenticationOuterIdentityBlock" style="display: none;">
<tr>
<td class="orionSummaryHeader">
<orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
<td class="orionSummaryColumn">
<orion:textbox id="authenticationOuterIdentity" size="30" />
</td>
</tr>
</tbody>
</table>
document.getElementById("elementID").scrollIntoView();
Same thing, but wrapping it in a function:
function scrollIntoView(eleID) {
var e = document.getElementById(eleID);
if (!!e && e.scrollIntoView) {
e.scrollIntoView();
}
}
This even works in an IFrame on an iPhone.
Example of using getElementById: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])
x*y
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit x*y
1000000 loops, best of 3: 421 ns per loop
np.multiply(x,y)
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
Both np.multiply
and *
would yield element wise multiplication known as the Hadamard Product
%timeit
is ipython magic
There is no way to do this. Your options are to use a JavaScript or a CSS block.
Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.
Forgive me for being a Stack virgin... I'm not sure how to reply to Brian Ramsay's answer...
Using round will not work for second values between 59.5 and 59.99999. The second value will be 60 during this period. Use trunc instead...
double progress;
int minutes = floor(progress/60);
int seconds = trunc(progress - minutes * 60);
Add the following line to the beginning script1.py
#!/usr/bin/env python
and then make the script executable:
$ chmod +x script1.py
If the script resides in a directory that appears in your PATH
variable, you can simply type
$ script1.py
Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH
.
$ ./script1.py
i fixed this by modifying php.ini
file at C:\wamp\bin\apache\apache2.4.9\bin\
curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"
first i was trying by modifying php.ini
file at C:\wamp\bin\php\php5.5.12\
and it didn't work.
hope this helps someone who is searching for the right php.ini
to modify
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
If you use this, you won’t get that error, and it is the simplest way to do that.
Try the CStr() function
Dim myVal as String;
Dim myNum as Integer;
myVal = "My number is:"
myVal = myVal & CStr(myNum);
You can use java.security.MessageDigest
with SHA
as your algorithm choice.
For reference,
You are using the wrong Request
class. If you want to use the Facade like: Request::ajax()
you have to import this class:
use Illuminate\Support\Facades\Request;
And not Illumiante\Http\Request
Another solution would be injecting an instance of the real request class:
public function index(Request $request){
if($request->ajax()){
return "AJAX";
}
(Now here you have to import Illuminate\Http\Request
)
Simply supplying the HTML of elements you want to add to a jQuery constructor $()
will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append()
method.
For example:
var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);
You could then populate this table programmatically, if you wished.
This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement
and then setting attributes like cellSpacing
and className
via JS.
Add this code on values anim
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:duration="@android:integer/config_longAnimTime"
android:fromXScale="0.2"
android:fromYScale="0.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"/>
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="@android:integer/config_longAnimTime"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
</set>
call on styles.xml
<style name="DialogScale">
<item name="android:windowEnterAnimation">@anim/scale_in</item>
<item name="android:windowExitAnimation">@anim/scale_out</item>
</style>
In Java code: set Onclick
public void onClick(View v) {
fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
// Dialogs.fab_onclick(R.style.DialogScale, "Scale");
}
setup on method:
alertDialog.getWindow().getAttributes().windowAnimations = type;
The accepted answer definitely works, but somehow miss an important point.
The OP is asking for a dictionary sorted by it's keys
this is just not really possible and not what OrderedDict
is doing.
OrderedDict is maintaining the content of the dictionary in insertion order. First item inserted, second item inserted, etc.
>>> d = OrderedDict()
>>> d['foo'] = 1
>>> d['bar'] = 2
>>> d
OrderedDict([('foo', 1), ('bar', 2)])
>>> d = OrderedDict()
>>> d['bar'] = 2
>>> d['foo'] = 1
>>> d
OrderedDict([('bar', 2), ('foo', 1)])
Hencefore I won't really be able to sort the dictionary inplace, but merely to create a new dictionary where insertion order match key order. This is explicit in the accepted answer where the new dictionary is b.
This may be important if you are keeping access to dictionaries through containers. This is also important if you itend to change the dictionary later by adding or removing items: they won't be inserted in key order but at the end of dictionary.
>>> d = OrderedDict({'foo': 5, 'bar': 8})
>>> d
OrderedDict([('foo', 5), ('bar', 8)])
>>> d['alpha'] = 2
>>> d
OrderedDict([('foo', 5), ('bar', 8), ('alpha', 2)])
Now, what does mean having a dictionary sorted by it's keys ? That makes no difference when accessing elements by keys, this only matter when you are iterating over items. Making that a property of the dictionary itself seems like overkill. In many cases it's enough to sort keys() when iterating.
That means that it's equivalent to do:
>>> d = {'foo': 5, 'bar': 8}
>>> for k,v in d.iteritems(): print k, v
on an hypothetical sorted by key dictionary or:
>>> d = {'foo': 5, 'bar': 8}
>>> for k, v in iter((k, d[k]) for k in sorted(d.keys())): print k, v
Of course it is not hard to wrap that behavior in an object by overloading iterators and maintaining a sorted keys list. But it is likely overkill.
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
.hover()
function accepts two function arguments, one for mouseenter
event and one for mouseleave
event.
UITextField
is specifically one-line only.
Your Google search is correct, you need to use UITextView
instead of UITextField
for display and editing of multiline text.
In Interface Builder, add a UITextView
where you want it and select the "editable" box. It will be multiline by default.
It's going to be locale-dependent. Different locale, different default encoding.
This also works:
...
WHERE
(FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
(LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
(Title IS NULL OR Title = ISNULL(@Title, Title))
Python has a "not" operator, right? Is it not just "not"? As in,
return not bool
Here is a basic implementation of writing and then reading json
file using json4s
.
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
import java.io._
import scala.io.Source
object MyObject { def main(args: Array[String]) {
val myMap = Map("a" -> List(3,4), "b" -> List(7,8))
// writing a file
val jsonString = pretty(render(myMap))
val pw = new PrintWriter(new File("my_json.json"))
pw.write(jsonString)
pw.close()
// reading a file
val myString = Source.fromFile("my_json.json").mkString
println(myString)
val myJSON = parse(myString)
println(myJSON)
// Converting from JOjbect to plain object
implicit val formats = DefaultFormats
val myOldMap = myJSON.extract[Map[String, List[Int]]]
println(myOldMap)
}
}
If you know the folder you want to navigate to, find the index of it then substring.
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
One liner:
var yesterday = new Date(Date.now() - 864e5); // 864e5 == 86400000 == 24*60*60*1000
For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)
I hope will help someone.
var sendEmail = function(somedata){
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL,
// you can try with TLS, but port is then 587
auth: {
user: '***@gmail.com', // Your email id
pass: '****' // Your password
}
};
var transporter = nodemailer.createTransport(smtpConfig);
// replace hardcoded options with data passed (somedata)
var mailOptions = {
from: '[email protected]', // sender address
to: '[email protected]', // list of receivers
subject: 'Test email', // Subject line
text: 'this is some text', //, // plaintext body
html: '<b>Hello world ?</b>' // You can choose to send an HTML body instead
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
return false;
}else{
console.log('Message sent: ' + info.response);
return true;
};
});
}
exports.contact = function(req, res){
// call sendEmail function and do something with it
sendEmail(somedata);
}
all the config are listed here (including examples)
Something quick and dirty:
<script type='text/javascript'>
function del_tr(remtr)
{
while((remtr.nodeName.toLowerCase())!='tr')
remtr = remtr.parentNode;
remtr.parentNode.removeChild(remtr);
}
function del_id(id)
{
del_tr(document.getElementById(id));
}
</script>
if you place
<a href='' onclick='del_tr(this);return false;'>x</a>
anywhere within the row you want to delete, than its even working without any ids
This is what I did at the end of the day - works fine now :
@Override
public void onClick(View v) {
my_button.setBackgroundResource(R.drawable.icon);
// SLEEP 2 SECONDS HERE ...
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
my_button.setBackgroundResource(R.drawable.defaultcard);
}
});
}
}, 2000);
}
It's a little ugly (due to the scaling up), but it works on most newer browsers:
input[type=checkbox]_x000D_
{_x000D_
/* Double-sized Checkboxes */_x000D_
-ms-transform: scale(2); /* IE */_x000D_
-moz-transform: scale(2); /* FF */_x000D_
-webkit-transform: scale(2); /* Safari and Chrome */_x000D_
-o-transform: scale(2); /* Opera */_x000D_
transform: scale(2);_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
/* Might want to wrap a span around your checkbox text */_x000D_
.checkboxtext_x000D_
{_x000D_
/* Checkbox text */_x000D_
font-size: 110%;_x000D_
display: inline;_x000D_
}
_x000D_
<input type="checkbox" name="optiona" id="opta" checked />_x000D_
<span class="checkboxtext">_x000D_
Option A_x000D_
</span>_x000D_
<input type="checkbox" name="optionb" id="optb" />_x000D_
<span class="checkboxtext">_x000D_
Option B_x000D_
</span>_x000D_
<input type="checkbox" name="optionc" id="optc" />_x000D_
<span class="checkboxtext">_x000D_
Option C_x000D_
</span>
_x000D_
My solution was uninstalling and installing the PHP instance (7.0 in my case) again:
sudo apt-get purge php7.0
sudo apt-get install php7.0
After that you will need to restart the Apache service:
sudo service apache2 restart
Finally, verify again in your browser with your localhost or IP address.
It's very simple to implement - you should use TestContext
property and TestPropertyAttribute
.
public TestContext TestContext { get; set; }
private List<string> GetProperties()
{
return TestContext.Properties
.Cast<KeyValuePair<string, object>>()
.Where(_ => _.Key.StartsWith("par"))
.Select(_ => _.Value as string)
.ToList();
}
//usage
[TestMethod]
[TestProperty("par1", "http://getbootstrap.com/components/")]
[TestProperty("par2", "http://www.wsj.com/europe")]
public void SomeTest()
{
var pars = GetProperties();
//...
}
I prepared few extension methods to simplify access to the TestContext
property and act like we have several test cases. See example with processing simple test properties here:
[TestMethod]
[TestProperty("fileName1", @".\test_file1")]
[TestProperty("fileName2", @".\test_file2")]
[TestProperty("fileName3", @".\test_file3")]
public void TestMethod3()
{
TestContext.GetMany<string>("fileName").ForEach(fileName =>
{
//Arrange
var f = new FileInfo(fileName);
//Act
var isExists = f.Exists;
//Asssert
Assert.IsFalse(isExists);
});
}
and example with creating complex test objects:
[TestMethod]
//Case 1
[TestProperty(nameof(FileDescriptor.FileVersionId), "673C9C2D-A29E-4ACC-90D4-67C52FBA84E4")]
//...
public void TestMethod2()
{
//Arrange
TestContext.For<FileDescriptor>().Fill(fi => fi.FileVersionId).Fill(fi => fi.Extension).Fill(fi => fi.Name).Fill(fi => fi.CreatedOn, new CultureInfo("en-US", false)).Fill(fi => fi.AccessPolicy)
.ForEach(fileInfo =>
{
//Act
var fileInfoString = fileInfo.ToString();
//Assert
Assert.AreEqual($"Id: {fileInfo.FileVersionId}; Ext: {fileInfo.Extension}; Name: {fileInfo.Name}; Created: {fileInfo.CreatedOn}; AccessPolicy: {fileInfo.AccessPolicy};", fileInfoString);
});
}
Take a look to the extension methods and set of samples for more details.
@Mikael Svenson's answer is correct. I just wanted to add a small addition to it:
The Messagebox icon can also be included has an additional property like below:
DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently
fs = 100 # sample rate
f = 2 # the frequency of the signal
x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs))
#this instruction can only be used with IPython Notbook.
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)
my solution is this:
cd android
and then:
./gradlew assembleMyBuild --stacktrace
I am coming here after searching google and change thing at my-end.
So I just change this sample and it will work with jquery at run-time.
$('select[name*="homepage_select"]').removeAttr('multiple')
From Windows command line:
set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
To set the PYTHONPATH permanently, add the line to your autoexec.bat
. Alternatively, if you edit the system variable through the System Properties, it will also be changed permanently.
Goto the Solution properties -> on Build right side you see the startup project type. here you need to select the console appication/windows appication.
public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
if (inputStream.isPresent()) {
ByteArrayOutputStream outpString base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));ut = new ByteArrayOutputStream();
FileCopyUtils.copy(inputStream.get(), output);
//TODO retrieve content type from file, & replace png below with it
return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
}
return Optional.empty();
I have a Toolbar in my Activity and a Base Activity that overrides all Titles. So I had to use setTitle in onResume() in the Activity like so:
@Override
protected void onResume() {
super.onResume();
toolbar.setTitle(R.string.title);
}
Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity
to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.
If you are doing automatic testing (in which you also create users) this might be a probable scenario.
In this case you need to revert to queries like:
SELECT pg_terminate_backend(procpid)
FROM pg_stat_get_activity(NULL::integer)
WHERE datid=(SELECT oid from pg_database where datname = 'your_database');
NOTE: In 9.2+ you'll have change procpid
to pid
.
simply used the +
operator. Javascript concats strings with +
To answer your question, these should work as long as:
But, if I remember correctly, these values can be faked to an extent, so it's best not to rely on them.
My personal preference is to set the domain name as an environment variable in the apache2 virtual host:
# Virtual host
setEnv DOMAIN_NAME example.com
And read it in PHP:
// PHP
echo getenv(DOMAIN_NAME);
This, however, isn't applicable in all circumstances.
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
the file might be locked by another process, you need to copy it then load it as it says in this post
_JAVA_OPTIONS="-Xmx3G" mvn clean install
Following up to @edovino's answer, the way of clearing all of an application's preferences programmatically would be
private void clearPreferences() {
try {
// clearing app data
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");
} catch (Exception e) {
e.printStackTrace();
}
}
Warning: the application will force close.
Maybe usefull to someone. On a Windows system, you can let Windows do the job by calling the dir-command. I use an absolute path, like E:/mydir/mysubdir
.
<?php
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
I've coded up a helper class for doing this. You can see the code at github: https://github.com/quiqueqs/Toast-Expander/blob/master/src/com/thirtymatches/toasted/ToastedActivity.java
This is how you'd display a toast for 5 seconds (or 5000 milliseconds):
Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);
Below is the python function to do the same.
def sigmoid(x) :
return 1.0/(1+np.exp(-x))
Easy solution would be to apply : idxmax() function to get indices of rows with max values. This would filter out all the rows with max value in the group.
In [365]: import pandas as pd
In [366]: df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})
In [367]: df
Out[367]:
count mt sp val
0 3 S1 MM1 a
1 2 S1 MM1 n
2 5 S3 MM1 cb
3 8 S3 MM2 mk
4 10 S4 MM2 bg
5 1 S4 MM2 dgb
6 2 S2 MM4 rd
7 2 S2 MM4 cb
8 7 S2 MM4 uyi
### Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]
Out[368]:
count mt sp val
0 3 S1 MM1 a
2 5 S3 MM1 cb
3 8 S3 MM2 mk
4 10 S4 MM2 bg
8 7 S2 MM4 uyi
### Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values
Out[369]: array([0, 2, 3, 4, 8])
Here is another approach:
You can simply create an ESLint friendly object like this
const modal: IModal = {} as IModal;
Or a default instance based on the interface and with sensible defaults, if any
const defaultModal: IModal = {
content: "",
form: "",
href: "",
$form: {} as JQuery,
$message: {} as JQuery,
$modal: {} as JQuery,
$submits: {} as JQuery
};
Then variations of the default instance simply by overriding some properties
const confirmationModal: IModal = {
...defaultModal, // all properties/values from defaultModal
form: "confirmForm" // override form only
}
Not best answer but you can reuse an already created ca bundle using --cert
option of pip
, for instance:
pip install SQLAlchemy==1.1.15 --cert="C:\Users\myUser\certificates\my_ca-bundle.crt"
As pointed out by Brani, vector() is a solution, e.g.
newVector <- vector(mode = "numeric", length = 50)
will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.
aVector <- c(aVector, newScalar)
Example solution for adding the library to your PYTHONPATH.
Add the following line into your ~/.bashrc or just run it directly:
export PYTHONPATH="$PYTHONPATH:$HOME/.python"
Then link your required library into your ~/.python folder, e.g.
ln -s /home/user/work/project/foo ~/.python/
None of the above answers except Mr Vaibhav Kumar's are clear or not ambiguous. [sorry, no offense]
Both multi programming and tasking are same concept of switching task in processor, difference is in the concept and reason of the switching.
MProgramming: to not keep processor idle when active task needs longer IO or other non CPU response then, processor loads and works on another task that is not waiting for IO and ready for process.
MTasking: even after MPrograming, to user it may feel like only one task is executing and another is simply waiting to come to cpu. So the active task is also swapped from active CPU and kept aside and another task is brought in CPU for a very small fraction of human time[second], and swapped back to the earlier task again. In this way user will feel both task are alive in CPU at same time. But actually each task is active only once at a given CPU time[in micro or nano second]
And MProcessing is, like my computer have quad core, so I use 4 processor at a time, means 4 different multiprogramming instances happen in my machine. And these 4 processors does another numerous no of MTasking.
So MProcessing>MProgramming>Mtasking
And MThreading n another breakup of each task. that also to give user a happy life. Here multiple tasks[like word doc and media player] are not coming in picture, rather small subtasks like coloring of text on word and automatic spell check in word are part of same word executable.
not sure if I was able to make clear all confusions...
To aid in what has already been mentioned there is a very good overview of the Linux graphics stack at this blog: http://blog.mecheye.net/2012/06/the-linux-graphics-stack/
This explains X11/Wayland etc and how it all fits together. In addition to what has already been mentioned I think it's worth adding a bit about the following API's you can use for graphics in Linux:
Mesa - "Mesa is many things, but one of the major things it provides that it is most famous for is its OpenGL implementation. It is an open-source implementation of the OpenGL API."
Cairo - "cairo is a drawing library used either by applications like Firefox directly, or through libraries like GTK+, to draw vector shapes."
DRM (Direct Rendering Manager) - I understand this the least but its basically the kernel drivers that let you write graphics directly to framebuffer without going through X
or use this syntax:
$("#mainTable").css("width", "100px");
$("#mainTable").css("height", "200px");
In case you want to keep decimal number, try following example:
number = Math.Floor(number * 100000000) / 100000000;
You just need to get selenium package imported, that you can do from command prompt using the command
pip install selenium
When you have to use it in any IDE just import this package, no other documentation required to be imported
For Eg :
import selenium
print(selenium.__filepath__)
This is just a general command you may use in starting to check the filepath of selenium
You can use data:
URL in the src
:
var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';_x000D_
var iframe = document.querySelector('iframe');_x000D_
iframe.src = 'data:text/html,' + encodeURIComponent(html);
_x000D_
<iframe></iframe>
_x000D_
Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.
nir[0].length
Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.
You should be able to force your local revision to the remote repo by using
git push -f <remote> <branch>
(e.g. git push -f origin master
). Leaving off <remote>
and <branch>
will force push all local branches that have set --set-upstream
.
Just be warned, if other people are sharing this repository their revision history will conflict with the new one. And if they have any local commits after the point of change they will become invalid.
Update: Thought I would add a side-note. If you are creating changes that others will review, then it's not uncommon to create a branch with those changes and rebase periodically to keep them up-to-date with the main development branch. Just let other developers know this will happen periodically so they'll know what to expect.
Update 2: Because of the increasing number of viewers I'd like to add some additional information on what to do when your upstream
does experience a force push.
Say I've cloned your repo and have added a few commits like so:
D----E topic / A----B----C development
But later the development
branch is hit with a rebase
, which will cause me to receive an error like so when I run git pull
:
Unpacking objects: 100% (3/3), done. From <repo-location> * branch development -> FETCH_HEAD Auto-merging <files> CONFLICT (content): Merge conflict in <locations> Automatic merge failed; fix conflicts and then commit the result.
Here I could fix the conflicts and commit
, but that would leave me with a really ugly commit history:
C----D----E----F topic / / A----B--------------C' development
It might look enticing to use git pull --force
but be careful because that'll leave you with stranded commits:
D----E topic A----B----C' development
So probably the best option is to do a git pull --rebase
. This will require me to resolve any conflicts like before, but for each step instead of committing I'll use git rebase --continue
. In the end the commit history will look much better:
D'---E' topic / A----B----C' development
Update 3: You can also use the --force-with-lease
option as a "safer" force
push, as mentioned by Cupcake in his
answer:
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use
--force-with-lease
by reading any of the following:
Scanner scan = new Scanner (System.in);
for (int i=0; i<=4, i++){
System.out.printf("Enter value at index"+i+" :");
anArray[i]=scan.nextInt();
}
I got a text file originally generated on a Windows Machine by way of a Mac user and needed to import it into a Linux MySQL DB using the load data
command.
Although VIM displayed the '^M' character, none of the above worked for my particular problem, the data would import but was always corrupted in some way. The solution was pretty easy in the end (after much frustration).
Solution:
Executing dos2unix
TWICE on the same file did the trick! Using the file
command shows what is happening along the way.
$ file 'file.txt'
file.txt: ASCII text, with CRLF, CR line terminators
$ dos2unix 'file.txt'
dos2unix: converting file file.txt to UNIX format ...
$ file 'file.txt'
file.txt: ASCII text, with CRLF line terminators
$ dos2unix 'file.txt'
dos2unix: converting file file.txt to UNIX format ...
$ file 'file.txt'
file.txt: ASCII text
And the final version of the file imported perfectly into the database.
Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).
def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
return a
else:
mx = max(a,b)
mn = min(a,b)
result = []
# inclusive upper limit. If not needed, delete '+1' in the line below
while(mn < mx + 1):
# if step is positive we go from min to max
if s > 0:
result.append(mn)
mn += s
# if step is negative we go from max to min
if s < 0:
result.append(mx)
mx += s
return result
For instance, standard command list(range(1,-3))
returns empty list []
, while this function will return [-3,-2,-1,0,1]
Updated: now step may be negative. Thanks @Michael for his comment.
Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma
, where sigma
is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n)
, where s
is the standard deviation computed from your sample data and n
is your sample size.
Use MM
for months. mm
is for minutes.
DateTime.Now.ToString("dd/MM/yyyy");
You probably run this code at the begining an hour like (00:00
, 05.00
, 18.00
) and mm
gives minutes (00
) to your datetime.
From Custom Date and Time Format Strings
"mm" --> The minute, from 00 through 59.
"MM" --> The month, from 01 through 12.
Here is a DEMO
. (Which the month part of first line depends on which time do you run this code ;)
)
As for me, i need the view diraction:
in -> swipe from right
out -> swipe to left
Here works for me code:
slide_in_right.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="50%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
slide_out_left.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-50%p"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
transaction code:
inline fun FragmentActivity.setContentFragment(
containerViewId: Int,
backStack: Boolean = false,
isAnimate: Boolean = false,
f: () -> Fragment
): Fragment? {
val manager = supportFragmentManager
return f().apply {
manager.beginTransaction().let {
if (isAnimate)
it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
if (backStack) {
it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
} else {
it.replace(containerViewId, this, "Fr").commit()
}
}
}
}
Adding to the top voted answer and many ones above stressing the "more generic, better", I would like to dig a little bit more.
Map
is the structure contract while HashMap
is an implementation providing its own methods to deal with different real problems: how to calculate index, what is the capacity and how to increment it, how to insert, how to keep the index unique, etc.
Let's look into the source code:
In Map
we have the method of containsKey(Object key)
:
boolean containsKey(Object key);
JavaDoc:
boolean java.util.Map.containsValue(Object value)
Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value
v
such that(value==null ? v==null : value.equals(v))
. This operation will probably require time linear in the map size for most implementations of the Map interface.Parameters:value
value whose presence in this map is to betested
Returns:true
if this map maps one or more keys to the specified
valueThrows:
ClassCastException - if the value is of an inappropriate type for this map (optional)
NullPointerException - if the specified value is null and this map does not permit null values (optional)
It requires its implementations to implement it, but the "how to" is at its freedom, only to ensure it returns correct.
In HashMap
:
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
It turns out that HashMap
uses hashcode to test if this map contains the key. So it has the benefit of hash algorithm.
I prefer to use "await" command and async functions to get rid of confusions of promises,
In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :
async function SubFunction(output){
// Call to database , returns a promise, like an Ajax call etc :
const response = await axios.get( GetApiHost() + '/api/some_endpoint')
// Return :
return response;
}
and then I would call this function from main function :
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
Noting that I returned both main function and sub function to async functions here.
Need to specify two attributes, table-layout:fixed
on table
and white-space:nowrap;
on the cells. You also need to move the overflow:hidden;
to the cells too
table { width:250px;table-layout:fixed; }
table tr { height:1em; }
td { overflow:hidden;white-space:nowrap; }
Here's a Demo . Tested in Firefox 3.5.3 and IE 7
Timmerman's solution works great when running the code, but if you don't want to get Undefined name
errors when using pyflakes or a similar linter you could use the following instead:
try:
import __builtin__
input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
pass
I just encountered this extremely frustrating error and lost the better part of an hour to it, for lack of a workable answer online. I confirmed in Firebug that I was hitting the CDN for both jQuery and validation.
In the end, changing this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js"></script>
to this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
was all I needed.
My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:
CREATE TABLE book (
id INT AUTO_INCREMENT NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL,
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
With the plugin: jQuery Selection Box. You can do this:
var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
Use \W
which is equivalent to [^a-zA-Z0-9_]
. Check the documentation, https://docs.python.org/2/library/re.html
Import re
s = 'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'
update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.
Another nice and efficient approach - is to pass rows for insertion as 1 argument, which is array of json objects.
E.g. you passing argument:
[ {id: 18, score: 1}, { id: 19, score: 5} ]
It is array, which may contain any amount of objects inside. Then your SQL looks like:
INSERT INTO links (parent_id, child_id, score)
SELECT 123, (r->>'id')::int, (r->>'score')::int
FROM unnest($1::json[]) as r
Notice: Your postgress must be new enough, to support json
Run This Query:
*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
>
> -- --------------------------------------------------------
>
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
>
> -- --------------------------------------------------------
>
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> -- 'pma'@localhost;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__bookmark`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__bookmark` ( `id` int(10) unsigned
> NOT NULL auto_increment, `dbase` varchar(255) NOT NULL default '',
> `user` varchar(255) NOT NULL default '', `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '', `query` text NOT NULL,
> PRIMARY KEY (`id`) ) COMMENT='Bookmarks' DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__column_info`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__column_info` ( `id` int(5) unsigned
> NOT NULL auto_increment, `db_name` varchar(64) NOT NULL default '',
> `table_name` varchar(64) NOT NULL default '', `column_name`
> varchar(64) NOT NULL default '', `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '', `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '', `transformation` varchar(255)
> NOT NULL default '', `transformation_options` varchar(255) NOT NULL
> default '', `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',
> PRIMARY KEY (`id`), UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) ) COMMENT='Column information
> for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__history`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__history` ( `id` bigint(20) unsigned
> NOT NULL auto_increment, `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '', `table` varchar(64) NOT NULL
> default '', `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP, `sqlquery` text NOT NULL, PRIMARY KEY (`id`),
> KEY `username` (`username`,`db`,`table`,`timevalue`) ) COMMENT='SQL
> history for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__pdf_pages`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` ( `db_name` varchar(64)
> NOT NULL default '', `page_nr` int(10) unsigned NOT NULL
> auto_increment, `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '', PRIMARY KEY (`page_nr`), KEY `db_name`
> (`db_name`) ) COMMENT='PDF relation pages for phpMyAdmin' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__recent`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__recent` ( `username` varchar(64)
> NOT NULL, `tables` text NOT NULL, PRIMARY KEY (`username`) )
> COMMENT='Recently accessed tables' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__favorite`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__favorite` ( `username` varchar(64)
> NOT NULL, `tables` text NOT NULL, PRIMARY KEY (`username`) )
> COMMENT='Favorite tables' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_uiprefs`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` ( `username`
> varchar(64) NOT NULL, `db_name` varchar(64) NOT NULL, `table_name`
> varchar(64) NOT NULL, `prefs` text NOT NULL, `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP, PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__relation`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__relation` ( `master_db` varchar(64)
> NOT NULL default '', `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '', `foreign_db`
> varchar(64) NOT NULL default '', `foreign_table` varchar(64) NOT
> NULL default '', `foreign_field` varchar(64) NOT NULL default '',
> PRIMARY KEY (`master_db`,`master_table`,`master_field`), KEY
> `foreign_field` (`foreign_db`,`foreign_table`) ) COMMENT='Relation
> table' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_coords`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_coords` ( `db_name`
> varchar(64) NOT NULL default '', `table_name` varchar(64) NOT NULL
> default '', `pdf_page_number` int(11) NOT NULL default '0', `x`
> float unsigned NOT NULL default '0', `y` float unsigned NOT NULL
> default '0', PRIMARY KEY (`db_name`,`table_name`,`pdf_page_number`)
> ) COMMENT='Table coordinates for phpMyAdmin PDF output' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__table_info`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__table_info` ( `db_name` varchar(64)
> NOT NULL default '', `table_name` varchar(64) NOT NULL default '',
> `display_field` varchar(64) NOT NULL default '', PRIMARY KEY
> (`db_name`,`table_name`) ) COMMENT='Table information for
> phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__tracking`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__tracking` ( `db_name` varchar(64)
> NOT NULL, `table_name` varchar(64) NOT NULL, `version` int(10)
> unsigned NOT NULL, `date_created` datetime NOT NULL,
> `date_updated` datetime NOT NULL, `schema_snapshot` text NOT NULL,
> `schema_sql` text, `data_sql` longtext, `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL, `tracking_active`
> int(1) unsigned NOT NULL default '1', PRIMARY KEY
> (`db_name`,`table_name`,`version`) ) COMMENT='Database changes
> tracking for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__userconfig`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__userconfig` ( `username`
> varchar(64) NOT NULL, `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `config_data` text
> NOT NULL, PRIMARY KEY (`username`) ) COMMENT='User preferences
> storage for phpMyAdmin' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__users`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__users` ( `username` varchar(64) NOT
> NULL, `usergroup` varchar(64) NOT NULL, PRIMARY KEY
> (`username`,`usergroup`) ) COMMENT='Users and their assignments to
> user groups' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__usergroups`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__usergroups` ( `usergroup`
> varchar(64) NOT NULL, `tab` varchar(64) NOT NULL, `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N', PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) ) COMMENT='User groups with configured
> menu items' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__navigationhiding`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` ( `username`
> varchar(64) NOT NULL, `item_name` varchar(64) NOT NULL,
> `item_type` varchar(64) NOT NULL, `db_name` varchar(64) NOT NULL,
> `table_name` varchar(64) NOT NULL, PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )
> COMMENT='Hidden items of navigation tree' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__savedsearches`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` ( `id` int(5)
> unsigned NOT NULL auto_increment, `username` varchar(64) NOT NULL
> default '', `db_name` varchar(64) NOT NULL default '',
> `search_name` varchar(64) NOT NULL default '', `search_data` text
> NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> ) COMMENT='Saved searches' DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__central_columns`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__central_columns` ( `db_name`
> varchar(64) NOT NULL, `col_name` varchar(64) NOT NULL, `col_type`
> varchar(64) NOT NULL, `col_length` text, `col_collation`
> varchar(64) NOT NULL, `col_isNull` boolean NOT NULL, `col_extra`
> varchar(255) default '', `col_default` text, PRIMARY KEY
> (`db_name`,`col_name`) ) COMMENT='Central list of columns' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__designer_settings`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` ( `username`
> varchar(64) NOT NULL, `settings_data` text NOT NULL, PRIMARY KEY
> (`username`) ) COMMENT='Settings related to Designer' DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
>
> -- --------------------------------------------------------
>
> --
> -- Table structure for table `pma__export_templates`
> --
>
> CREATE TABLE IF NOT EXISTS `pma__export_templates` ( `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT, `username` varchar(64) NOT NULL,
> `export_type` varchar(10) NOT NULL, `template_name` varchar(64) NOT
> NULL, `template_data` text NOT NULL, PRIMARY KEY (`id`), UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> ) COMMENT='Saved export templates' DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*
Open This File :
C:\xampp\phpMyAdmin\config.inc.php
Clear and Past this Code :
> --------------------------------------------------------- <?php /** * Debian local configuration file * * This file overrides the settings
> made by phpMyAdmin interactive setup * utility. * * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz * * NOTE:
> do not add security sensitive data to this file (like passwords) *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still * want to do this, make sure to properly secure the access to
> this file * (also on the filesystem level). */ /** * Server(s)
> configuration */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1]. Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
> /* Authentication type */
> $cfg['Servers'][$i]['auth_type'] = 'cookie';
> /* Server parameters */
> if (empty($dbserver)) $dbserver = 'localhost';
> $cfg['Servers'][$i]['host'] = $dbserver;
> if (!empty($dbport)) {
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> $cfg['Servers'][$i]['port'] = $dbport;
> }
> //$cfg['Servers'][$i]['compress'] = false;
> /* Select mysqli if your server has it */
> $cfg['Servers'][$i]['extension'] = 'mysqli';
> /* Optional: User for advanced features */
> $cfg['Servers'][$i]['controluser'] = $dbuser;
> $cfg['Servers'][$i]['controlpass'] = $dbpass;
> /* Optional: Advanced phpMyAdmin features */
> $cfg['Servers'][$i]['pmadb'] = $dbname;
> $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
> $cfg['Servers'][$i]['relation'] = 'pma_relation';
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
> $cfg['Servers'][$i]['history'] = 'pma_history';
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
> /* Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */
> // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
> /* Advance to next server for rest of config */
> $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* * End of servers
> configuration */ /* * Directories for saving/loading files from
> server */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';
------------------------------------------
i Solve My Problem Through this Method
If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):
# 1) Get back to the main body page
driver.switch_to.default_content()
# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js:
# 3) Read the jquery from a file
jquery = jquery_js.read()
# 4) Load jquery lib
driver.execute_script(jquery)
# 5) Execute your command
driver.execute_script('$("#myId").click()')
You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679
As mentioned by Stuart McLaughlin, make sure you get the x86 version even if you use a 64-bits OS because PHP needs some 32-bit libraries.
An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii')
.
If you are creating other batch files from your outputs then put a line like this in your batch file
echo %pathname%\foo.exe >part2.txt
then you can have your defined part1.txt
and part3.txt
already done and have your batch
copy part1.txt + part2.txt +part3.txt thebatyouwanted.bat
To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions below to create one using Keychain Access.
Create a CSR file. In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.
Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.
In the Certificate Information window, enter the following information: In the User Email Address field, enter your email address. In the Common Name field, create a name for your private key (e.g., John Doe Dev Key). The CA Email Address field should be left empty. In the "Request is" group, select the "Saved to disk" option. Click Continue within Keychain Access to complete the CSR generating process.
function mydump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') {
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') {
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += mydump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else {
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
Happen to have a task on pivot. Below works for me as tested just now on 11g:
select * from
(
select ID, COUNTRY_NAME, TOTAL_COUNT from ONE_TABLE
)
pivot(
SUM(TOTAL_COUNT) for COUNTRY_NAME in (
'Canada', 'USA', 'Mexico'
)
);
Your settings must be incorrect.
Go to http://www.facebook.com/developers/ and edit the application you're working on.
On the "website" tab, look for "Site URL". This should be set to your website's URL "http://yoursite.com/"
Note that if you're using subdomains, you'll also need to update "Site Domain" to be "yoursite.com"
Start up R in a fresh session and paste this in:
library(ggplot2)
df <- structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82,
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
c("1999", "2002", "2005", "2008")))), .Names = c("year",
"pollution"), row.names = c(NA, -4L), class = "data.frame")
df[] <- lapply(df, as.numeric) # make all columns numeric
ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = "Year",
y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
You could also do it with PowerShell:
Get-WmiObject win32_service -filter "Name='My Service'" `
| Invoke-WmiMethod -Name Change `
-ArgumentList @($null,$null,$null,$null,$null, `
"C:\Program Files (x86)\My Service\NewName.EXE")
Or:
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
-Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"
when you bind localhost
or 127.0.0.1
, it means you can only connect to your service from local.
you cannot bind 10.0.0.1
because it not belong to you, you can only bind ip owned by your computer
you can bind 0.0.0.0
because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip
If you have to deal with data that large you'll need to split it up into manageable chunks. It won't all fit into memory on any small computer. You can probably load a portion of the data from disk (whatever reasonably fits), perform your calculations and changes to it, store it to disk, then repeat until complete.
Parsing argument based on standard input ( --key=value
)
const argv = (() => {
const arguments = {};
process.argv.slice(2).map( (element) => {
const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
if ( matches ){
arguments[matches[1]] = matches[2]
.replace(/^['"]/, '').replace(/['"]$/, '');
}
});
return arguments;
})();
Command example
node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
Result of argv: console.log(argv)
{
name: "stackoverflow",
id: "10",
text: "Hello World"
}
Please, ckeck this simple example. You can get values in select2 multi.
var values = $('#id-select2-multi').val();
console.log(values);
You're looking for:
.is(':visible')
Although you should probably change your selector to use jQuery considering you're using it in other places anyway:
if($('#testElement').is(':visible')) {
// Code
}
It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible')
on the child will return false
(which makes sense).
:visible
has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible
):
Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!
Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.
Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle()
:
function toggleTestElement() {
$('#testElement').fadeToggle('fast');
}
You could define a function that repeats the passed function N times.
def repeat_fun(times, f):
for i in range(times): f()
If you want to make it even more flexible, you can even pass arguments to the function being repeated:
def repeat_fun(times, f, *args):
for i in range(times): f(*args)
Usage:
>>> def do():
... print 'Doing'
...
>>> def say(s):
... print s
...
>>> repeat_fun(3, do)
Doing
Doing
Doing
>>> repeat_fun(4, say, 'Hello!')
Hello!
Hello!
Hello!
Hello!
Your selector won't select the input field, and if it did it would return a jQuery object. Try this:
$('#test2').is(':checked');
To find the DLL, go to your 64-bit machine and open the registry. Find the key called HKEY_CLASSES_ROOT\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32
. This key will have the filename of the DLL as its default value.
If you solved the problem on your 64-bit machine by recompiling your project for x86, then you'll need to look in the 32-bit portion of the registry instead of in the normal place. This is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32
.
If the DLL is built for 32 bits then you can use it directly on your 32-bit machine. If it's built for 64 bits then you'll have to contact the vendor and get a 32-bit version from them.
When you have the DLL, register it by running c:\windows\system32\regsvr32.exe.
var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
// There exists one with size 200 and is stored in item now
}
else {
// There is no PricePublicModel with size 200
}
From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
ConfigurationManager.AppSettings
is actually a property, so you need to use square brackets.
Overall, here's what you need to do:
SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.
Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.
for(int j=0;j<30;j++) {
LinearLayout childLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
childLayout.setLayoutParams(linearParams);
TextView mType = new TextView(MainActivity.this);
TextView mValue = new TextView(MainActivity.this);
mType.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1f));
mValue.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1f));
mType.setTextSize(17);
mType.setPadding(5, 3, 0, 3);
mType.setTypeface(Typeface.DEFAULT_BOLD);
mType.setGravity(Gravity.LEFT | Gravity.CENTER);
mValue.setTextSize(16);
mValue.setPadding(5, 3, 0, 3);
mValue.setTypeface(null, Typeface.ITALIC);
mValue.setGravity(Gravity.LEFT | Gravity.CENTER);
mType.setText("111");
mValue.setText("111");
childLayout.addView(mValue, 0);
childLayout.addView(mType, 0);
linear.addView(childLayout);
}
For using the new progress bar
style="?android:attr/progressBarStyleHorizontal"
for the old grey color progress bar use
style="@android:style/Widget.ProgressBar.Horizontal"
in this one you have the option of changing the height by setting minHeight
The complete XML code is:
<ProgressBar
android:id="@+id/pbProcessing"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvProcessing"
android:indeterminateOnly="true"/>
indeterminateOnly is set to true for getting indeterminate horizontal progress bar
To avoid including a large framework, I think a simple homemade class can do the trick.
Example of class to handle named parameters:
public class NamedParamStatement {
public NamedParamStatement(Connection conn, String sql) throws SQLException {
int pos;
while((pos = sql.indexOf(":")) != -1) {
int end = sql.substring(pos).indexOf(" ");
if (end == -1)
end = sql.length();
else
end += pos;
fields.add(sql.substring(pos+1,end));
sql = sql.substring(0, pos) + "?" + sql.substring(end);
}
prepStmt = conn.prepareStatement(sql);
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return prepStmt.executeQuery();
}
public void close() throws SQLException {
prepStmt.close();
}
public void setInt(String name, int value) throws SQLException {
prepStmt.setInt(getIndex(name), value);
}
private int getIndex(String name) {
return fields.indexOf(name)+1;
}
private PreparedStatement prepStmt;
private List<String> fields = new ArrayList<String>();
}
Example of calling the class:
String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();
Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.
It seems that you need to wait for the page to be reloaded before clicking on the "Add" button. In this case you could wait for the "Add Item" element to become stale before clicking on the reloaded element:
WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");
// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
//trigger the reaload of the page
driver.findElement(By.id("...")).click();
// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));
// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();
alloca() is very useful if you can't use a standard local variable because its size would need to be determined at runtime and you can absolutely guarantee that the pointer you get from alloca() will NEVER be used after this function returns.
You can be fairly safe if you
The real danger comes from the chance that someone else will violate these conditions sometime later. With that in mind it's great for passing buffers to functions that format text into them :)
Your current location might not be available immediately, after the map fragment is initialized.
After set
googleMap.setMyLocationEnabled(true);
you have to wait until you see the blue dot shown on your MapView. Then
Location myLocation = googleMap.getMyLocation();
myLocation won't be null.
I think you better use the LocationClient instead, and implement your own LocationListener.onLocationChanged(Location l)
Receiving Location Updates will show you how to get current location from LocationClient
I faced this same problem today. The error was apt. By mistake, I added cyclic dependency. A was dependent on B. In my case, by mistake, apart from adding B as dependent to A. I added A as dependent to B too. It was a foolish mistake.
The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")
In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec-laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.
Do it like Andrey shows.
Instead of overflow:auto
, try overflow-y:auto
. Should work like a charm!
This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active
next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache
(where all of jQuery.data()
goes).
I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart()
and $.ajaxStop()
(which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.
When jQuery starts an AJAX request, this happens:
if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" );
}
This is what causes the $.ajaxStart()
event to fire, the number of connections just went from 0 to 1 (jQuery.active++
isn't 0 after this one, and !0 == true
), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend
abort via return false
or an ajax call complete
function runs):
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
This is what causes the $.ajaxStop()
event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
To create an environment named py37
with python 3.7, using the channel conda-forge and a list of packages:
conda create -y --name py37 python=3.7
conda install --force-reinstall -y -q --name py37 -c conda-forge --file requirements.txt
conda activate py37
...
conda deactivate
Flags explained:
-y
: Do not ask for confirmation.--force-reinstall
: Install the package even if it already exists.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderThe ansible-role dockpack.base_miniconda can manage conda environments and can be used to create a docker base image.
Alternatively you can create an environment.yml file instead of requirements.txt:
name: py37
channels:
- conda-forge
dependencies:
- python=3.7
- numpy=1.9.*
- pandas
Use this command to list the environments you have:
conda info --envs
Use this command to remove the environment:
conda env remove -n py37
this is what i did
first execute create database x
. x is the name of your old database eg the name of the mdf.
Then open sql sever configration and stop the sql sever.
There after browse to the location of your new created database it should be under program file, in my case is
C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQL\MSSQL\DATA
and repleace the new created mdf and Idf with the old files/database.
then simply restart the sql server and walla :)
Why choose between a traditional database and a NoSQL data store? Use both! The problem with NoSQL solutions (beyond the initial learning curve) is the lack of transactions -- you do all updates to MySQL and have MySQL populate a NoSQL data store for reads -- you then benefit from each technology's strengths. This does add more complexity, but you already have the MySQL side -- just add MongoDB, Cassandra, etc to the mix.
NoSQL datastores generally scale way better than a traditional DB for the same otherwise specs -- there is a reason why Facebook, Twitter, Google, and most start-ups are using NoSQL solutions. It's not just geeks getting high on new tech.
This error means the application pool to which your deployed application belongs is not in Integrated mode.
My usecase is:
I am on later versions of Selenium 3, and the login popup is not detected with driver.switchTo().alert();
- results in NoAlertPresentException
.
Just providing username:password
in the URL is not propagated from step 1 to 2 above.
My workaround:
import org.apache.http.client.utils.URIBuilder;
driver.get(...webapp_location...);
wait.until(ExpectedConditions.urlContains(...sso_server...));
URIBuilder uri = null;
try {
uri = new URIBuilder(driver.getCurrentUrl());
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
uri.setUserInfo(username, password);
driver.navigate().to(uri.toString());
Click Guard works well with Butter Knife
ClickGuard.guard(mPlayButton);
app[func].apply(this, args);
To remove first Character of string in PHP,
$string = "abcdef";
$new_string = substr($string, 1);
echo $new_string;
Generates: "bcdef"
You can use shorthand syntax as of Twig 1.12.0
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
I think it should be:
dataGridView1.Columns[0].HeaderCell.Value = "my text";
<a data-title="A Title" data-placement="top" data-html="true" data-content="<form><input type='text'/></form>" data-trigger="hover" rel="popover" class="btn btn-primary" id="test">Top popover</a>
just state data-html="true"
I'm not sure if you want to switch to the mail app itself or just open and send an email. For the latter option linked to a button IBAction:
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBAction func launchEmail(sender: AnyObject) {
var emailTitle = "Feedback"
var messageBody = "Feature request or bug report?"
var toRecipents = ["[email protected]"]
var mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toRecipents)
self.presentViewController(mc, animated: true, completion: nil)
}
func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
switch result {
case MFMailComposeResultCancelled:
print("Mail cancelled")
case MFMailComposeResultSaved:
print("Mail saved")
case MFMailComposeResultSent:
print("Mail sent")
case MFMailComposeResultFailed:
print("Mail sent failure: \(error?.localizedDescription)")
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
I have gitlab running with docker, this is what I did to fix my problem.
Found that inside docker /var/log/gitlab/sshd/current there were multiple occurences of a message:
Authentication refused: bad ownership or modes for file /var/opt/gitlab/.ssh/authorized_keys
After which I changed ownership of that file from 99:users to git:users with:
chown git:users authorized_keys
@Html.TextBoxFor(model => model.IssueDate, new { @class = "form-control", name = "inv_issue_date", id = "inv_issue_date", title = "Select Invoice Issue Date", placeholder = "dd/mm/yyyy", style = "text-align:center;" })
Well, Bootstrap Carousel has various parameters to control.
i.e.
Interval: Specifies the delay (in milliseconds) between each slide.
pause: Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.
wrap: Specifies whether the carousel should go through all slides continuously, or stop at the last slide
For your reference:
Fore more details please click here...
Hope this will help you :)
Note: This is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.
yourLabel.intrinsicContentSize.width
for Objective-C / Swift
Seems there's a typo (missing colon) in the JSON dict provided by jro.
The correct syntax would be:
jdata = json.load('{"uri": "http:", "foo": "bar"}')
This cleared it up for me when playing with the code.
Sounds like you want:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
You have some syntax issues with your script. Here is a fixed version:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
As per snapshot the main reason for error is that you are not defining c.tld in lib folder causes such error.
This lib content information about taglib
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
import sys
sys.dont_write_bytecode = True
Instead of using the body you could create a curtain with z-index
of 100 (to pick a number) and give the inside element a higher z-index
while all other elements have a lower z-index than the curtain.
See working example here: http://jsfiddle.net/Flandre/6JvFk/
jQuery:
$('#curtain').on("click", function(e) {
$(this).hide();
alert("clicked ouside of elements that stand out");
});
CSS:
.aboveCurtain
{
z-index: 200; /* has to have a higher index than the curtain */
position: relative;
background-color: pink;
}
#curtain
{
position: fixed;
top: 0px;
left: 0px;
height: 100%;
background-color: black;
width: 100%;
z-index:100;
opacity:0.5 /* change opacity to 0 to make it a true glass effect */
}
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d"
not dateFormat...
so
jQuery('#timePicker').datetimepicker({
format: 'd-m-y',
value: new Date()
});
Here's a nice little global function you can add for a nicer syntax:
func dispatch_on_main(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
And usage
dispatch_on_main {
// Do some UI stuff
}
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......
It seems to my case that Excel 2011 for Mac OS is not using Encoding.GetEncoding("10000") as i thought and wasted 2 days with but the same iso as on Microsoft OS. The best proof for this is to make a file in Excel 2011 for MAC with special chars, save it as CSV and then open it in MAC text editor and the chars are scrambled.
For me this approach worked - meaning that csv export on Excel 2011 on MAC OS has special western europeean chars inside:
Encoding isoMacOS = Encoding.GetEncoding("iso-8859-1");
Encoding defaultEncoding = Encoding.Default;
// Convert the string into a byte array.
byte[] defaultEncodingBytes = defaultEncoding.GetBytes(exportText);
// Perform the conversion from one encoding to the other.
byte[] ansiBytes = Encoding.Convert(defaultEncoding, isoMacOS, defaultEncodingBytes);
decodedString = isoMacOS.GetString(ansiBytes);
How about you store it like this? Maybe in username:password format, so
sebastion:password123
anotheruser:password321
Then you can use list($username,$password) = explode(':',file_get_contents('users.txt'));
to parse the data on your end.
An option --find-links does the job and it works from requirements.txt
file!
You can put package archives in some folder and take the latest one without changing the requirements file, for example requirements
:
.
+---requirements.txt
+---requirements
+---foo_bar-0.1.5-py2.py3-none-any.whl
+---foo_bar-0.1.6-py2.py3-none-any.whl
+---wiz_bang-0.7-py2.py3-none-any.whl
+---wiz_bang-0.8-py2.py3-none-any.whl
+---base.txt
+---local.txt
+---production.txt
Now in requirements/base.txt
put:
--find-links=requirements
foo_bar
wiz_bang>=0.8
A neat way to update proprietary packages, just drop new one in the folder
In this way you can install packages from local folder
AND pypi
with the same single call: pip install -r requirements/production.txt
PS. See my cookiecutter-djangopackage fork to see how to split requirements and use folder based requirements organization.
Try add min-width: 100%
to style of your textarea:
<textarea class="form-control" style="min-width: 100%"></textarea>
Without any additional packages:
true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)
getROC_AUC = function(probs, true_Y){
probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
val = unlist(probsSort$x)
idx = unlist(probsSort$ix)
roc_y = true_Y[idx];
stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)
auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}
aList = getROC_AUC(probs, true_Y)
stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)
plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")
System.out.println("wassup");
refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong);
is a reference to show that the input provided is wrong or there is some other error.
Most of the IDEs show this in red color (System.err.print
).
You should prefer the JPA methods most of the time, and the update
for batch processing tasks.
A JPA or Hibernate entity can be in one of the following four states:
The transition from one state to the other is done via the EntityManager or Session methods.
For instance, the JPA EntityManager
provides the following entity state transition methods.
The Hibernate Session
implements all the JPA EntityManager
methods and provides some additional entity state transition methods like save
, saveOrUpdate
and update
.
To change the state of an entity from Transient (New) to Managed (Persisted), we can use the persist
method offered by the JPA EntityManager
which is also inherited by the Hibernate Session
.
The
persist
method triggers aPersistEvent
which is handled by theDefaultPersistEventListener
Hibernate event listener.
Therefore, when executing the following test case:
doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
LOGGER.info(
"Persisting the Book entity with the id: {}",
book.getId()
);
});
Hibernate generates the following SQL statements:
CALL NEXT VALUE FOR hibernate_sequence
-- Persisting the Book entity with the id: 1
INSERT INTO book (
author,
isbn,
title,
id
)
VALUES (
'Vlad Mihalcea',
'978-9730228236',
'High-Performance Java Persistence',
1
)
Notice that the id
is assigned prior to attaching the Book
entity to the current Persistence Context. This is needed because the managed entities are stored in a Map
structure where the key is formed by the entity type and its identifier and the value is the entity reference. This is the reason why the JPA EntityManager
and the Hibernate Session
are known as the First-Level Cache.
When calling persist
, the entity is only attached to the currently running Persistence Context, and the INSERT can be postponed until the flush
is called.
The only exception is the IDENTITY
which triggers the INSERT right away since that's the only way it can get the entity identifier. For this reason, Hibernate cannot batch inserts for entities using the IDENTITY
generator.
The Hibernate-specific save
method predates JPA and it's been available since the beginning of the Hibernate project.
The
save
method triggers aSaveOrUpdateEvent
which is handled by theDefaultSaveOrUpdateEventListener
Hibernate event listener. Therefore, thesave
method is equivalent to theupdate
andsaveOrUpdate
methods.
To see how the save
method works, consider the following test case:
doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
Session session = entityManager.unwrap(Session.class);
Long id = (Long) session.save(book);
LOGGER.info(
"Saving the Book entity with the id: {}",
id
);
});
When running the test case above, Hibernate generates the following SQL statements:
CALL NEXT VALUE FOR hibernate_sequence
-- Saving the Book entity with the id: 1
INSERT INTO book (
author,
isbn,
title,
id
)
VALUES (
'Vlad Mihalcea',
'978-9730228236',
'High-Performance Java Persistence',
1
)
As you can see, the outcome is identical to the persist
method call. However, unlike persist
, the save
method returns the entity identifier.
The Hibernate-specific update
method is meant to bypass the dirty checking mechanism and force an entity update at the flush time.
The
update
method triggers aSaveOrUpdateEvent
which is handled by theDefaultSaveOrUpdateEventListener
Hibernate event listener. Therefore, theupdate
method is equivalent to thesave
andsaveOrUpdate
methods.
To see how the update
method works consider the following example which persists a Book
entity in one transaction, then it modifies it while the entity is in the detached state, and it forces the SQL UPDATE using the update
method call.
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
return book;
});
LOGGER.info("Modifying the Book entity");
_book.setTitle(
"High-Performance Java Persistence, 2nd edition"
);
doInJPA(entityManager -> {
Session session = entityManager.unwrap(Session.class);
session.update(_book);
LOGGER.info("Updating the Book entity");
});
When executing the test case above, Hibernate generates the following SQL statements:
CALL NEXT VALUE FOR hibernate_sequence
INSERT INTO book (
author,
isbn,
title,
id
)
VALUES (
'Vlad Mihalcea',
'978-9730228236',
'High-Performance Java Persistence',
1
)
-- Modifying the Book entity
-- Updating the Book entity
UPDATE
book
SET
author = 'Vlad Mihalcea',
isbn = '978-9730228236',
title = 'High-Performance Java Persistence, 2nd edition'
WHERE
id = 1
Notice that the UPDATE
is executed during the Persistence Context flush, right before commit, and that's why the Updating the Book entity
message is logged first.
@SelectBeforeUpdate
to avoid unnecessary updatesNow, the UPDATE is always going to be executed even if the entity was not changed while in the detached state. To prevent this, you can use the @SelectBeforeUpdate
Hibernate annotation which will trigger a SELECT
statement that fetched loaded state
which is then used by the dirty checking mechanism.
So, if we annotate the Book
entity with the @SelectBeforeUpdate
annotation:
@Entity(name = "Book")
@Table(name = "book")
@SelectBeforeUpdate
public class Book {
//Code omitted for brevity
}
And execute the following test case:
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
return book;
});
doInJPA(entityManager -> {
Session session = entityManager.unwrap(Session.class);
session.update(_book);
});
Hibernate executes the following SQL statements:
INSERT INTO book (
author,
isbn,
title,
id
)
VALUES (
'Vlad Mihalcea',
'978-9730228236',
'High-Performance Java Persistence',
1
)
SELECT
b.id,
b.author AS author2_0_,
b.isbn AS isbn3_0_,
b.title AS title4_0_
FROM
book b
WHERE
b.id = 1
Notice that, this time, there is no UPDATE
executed since the Hibernate dirty checking mechanism has detected that the entity was not modified.
The Hibernate-specific saveOrUpdate
method is just an alias for save
and update
.
The
saveOrUpdate
method triggers aSaveOrUpdateEvent
which is handled by theDefaultSaveOrUpdateEventListener
Hibernate event listener. Therefore, theupdate
method is equivalent to thesave
andsaveOrUpdate
methods.
Now, you can use saveOrUpdate
when you want to persist an entity or to force an UPDATE
as illustrated by the following example.
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(book);
return book;
});
_book.setTitle("High-Performance Java Persistence, 2nd edition");
doInJPA(entityManager -> {
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(_book);
});
NonUniqueObjectException
One problem that can occur with save
, update
, and saveOrUpdate
is if the Persistence Context already contains an entity reference with the same id and of the same type as in the following example:
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(book);
return book;
});
_book.setTitle(
"High-Performance Java Persistence, 2nd edition"
);
try {
doInJPA(entityManager -> {
Book book = entityManager.find(
Book.class,
_book.getId()
);
Session session = entityManager.unwrap(Session.class);
session.saveOrUpdate(_book);
});
} catch (NonUniqueObjectException e) {
LOGGER.error(
"The Persistence Context cannot hold " +
"two representations of the same entity",
e
);
}
Now, when executing the test case above, Hibernate is going to throw a NonUniqueObjectException
because the second EntityManager
already contains a Book
entity with the same identifier as the one we pass to update
, and the Persistence Context cannot hold two representations of the same entity.
org.hibernate.NonUniqueObjectException:
A different object with the same identifier value was already associated with the session : [com.vladmihalcea.book.hpjp.hibernate.pc.Book#1]
at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:651)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:227)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:674)
To avoid the NonUniqueObjectException
, you need to use the merge
method offered by the JPA EntityManager
and inherited by the Hibernate Session
as well.
The merge
fetches a new entity snapshot from the database if there is no entity reference found in the Persistence Context, and it copies the state of the detached entity passed to the merge
method.
The
merge
method triggers aMergeEvent
which is handled by theDefaultMergeEventListener
Hibernate event listener.
To see how the merge
method works consider the following example which persists a Book
entity in one transaction, then it modifies it while the entity is in the detached state, and passes the detached entity to merge
in a subsequence Persistence Context.
Book _book = doInJPA(entityManager -> {
Book book = new Book()
.setIsbn("978-9730228236")
.setTitle("High-Performance Java Persistence")
.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
return book;
});
LOGGER.info("Modifying the Book entity");
_book.setTitle(
"High-Performance Java Persistence, 2nd edition"
);
doInJPA(entityManager -> {
Book book = entityManager.merge(_book);
LOGGER.info("Merging the Book entity");
assertFalse(book == _book);
});
When running the test case above, Hibernate executed the following SQL statements:
INSERT INTO book (
author,
isbn,
title,
id
)
VALUES (
'Vlad Mihalcea',
'978-9730228236',
'High-Performance Java Persistence',
1
)
-- Modifying the Book entity
SELECT
b.id,
b.author AS author2_0_,
b.isbn AS isbn3_0_,
b.title AS title4_0_
FROM
book b
WHERE
b.id = 1
-- Merging the Book entity
UPDATE
book
SET
author = 'Vlad Mihalcea',
isbn = '978-9730228236',
title = 'High-Performance Java Persistence, 2nd edition'
WHERE
id = 1
Notice that the entity reference returned by merge
is different than the detached one we passed to the merge
method.
Now, although you should prefer using JPA merge
when copying the detached entity state, the extra SELECT
can be problematic when executing a batch processing task.
For this reason, you should prefer using update
when you are sure that there is no entity reference already attached to the currently running Persistence Context and that the detached entity has been modified.
To persist an entity, you should use the JPA persist
method. To copy the detached entity state, merge
should be preferred. The update
method is useful for batch processing tasks only. The save
and saveOrUpdate
are just aliases to update
and you should not probably use them at all.
Some developers call save
even when the entity is already managed, but this is a mistake and triggers a redundant event since, for managed entities, the UPDATE is automatically handled at the Persistence context flush time.
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
You could simply have just done:
var varAppend = "?single";
window.location.href = window.location.href.replace(".com",".com" + varAppend);
Unlike the other answers provided, there is no needless conditional check. If you design your project properly, you'll let the interface make the decision making and calling that statement whenever an event has been triggered.
Since there will only be one ".com" in your url, it will just replace .com
with .com?single
. I just added varAppend
just in case you want to make it easier to modify the code in the future with different kinds of url variables.
One other note:
The .replace
works by adding to the href since href returns a string containing the full url address information.
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Using the cursor based variations above as a starting point, the script below will just output a set of UPDATE statements to set to DATABASE_DEFAULT, it won't actually do the UPDATES.
It supports schema, the full set of char and text types and retains the existing NULL / NOT NULL.
I plan to use the output to find to statements that fail in a lower environment and then manually adapt the resulting script to drop and recreate the constraints as needed.
DECLARE @collate nvarchar(100);
DECLARE @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @max_length_str nvarchar(100);
DECLARE @is_nullable bit;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
SET @collate = 'DATABASE_DEFAULT';
DECLARE local_table_cursor CURSOR FOR
SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy
INNER JOIN sys.objects o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1
ORDER BY s.[name], o.[name]
OPEN local_table_cursor FETCH NEXT FROM local_table_cursor INTO @schema,@table
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE local_change_cursor CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, col.CHARACTER_MAXIMUM_LENGTH
, c.column_id
, c.is_nullable
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
JOIN INFORMATION_SCHEMA.COLUMNS col on col.COLUMN_NAME = c.name and c.object_id = OBJECT_ID(col.TABLE_NAME)
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id = OBJECT_ID(@schema+'.'+@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%')
ORDER BY c.column_id
OPEN local_change_cursor
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable
WHILE @@FETCH_STATUS = 0
BEGIN
SET @max_length_str = @max_length
IF (@max_length = -1) SET @max_length_str = 'max'
IF (@max_length > 4000) SET @max_length_str = '4000'
SET @sql =
CASE
WHEN @data_type like '%text%'
THEN 'ALTER TABLE [' + @schema+ '].['+ @table + '] ALTER COLUMN [' + @column_name + '] ' + @data_type + ' COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
ELSE 'ALTER TABLE [' + @schema+ '].['+ @table + '] ALTER COLUMN [' + @column_name + '] ' + @data_type + '(' + @max_length_str + ') COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
END
PRINT @sql
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable
END
CLOSE local_change_cursor
DEALLOCATE local_change_cursor
FETCH NEXT FROM local_table_cursor
INTO @schema, @table
END
CLOSE local_table_cursor
DEALLOCATE local_table_cursor
GO
Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.
However, you can convert strings to numbers like this:
pd.Series(['123', '42']).astype(float)
instead of float(series)
Check encoding and language:
$ echo $LC_CTYPE
ISO-8859-1
$ echo $LANG
pt_BR
Get all languages:
$ locale -a
Change to pt_PT.utf8:
$ export LC_ALL=pt_PT.utf8
$ export LANG="$LC_ALL"
If you have the directory name in myDirectoryPath
,
import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}
Motion is an alternative to Zoneminder. It has a steeper setup curve as everything is configured via config files.However, the config files are nicely commented and it's easier than it sounds. It's very reliable once running as well.
To add a Foscam camera (mentioned above) use the following syntax to stream the video from the camera.
netcam_url http://<IPADDRESS>/videostream.cgi?user=admin?pwd=
Where the user is admin with a blank password (the default for Foscam cameras).
For really high uptime/reliablity consider using a monitoring tool such as Monit. This works well with Motion.
When webview is embedded in some custom view such that user almost believes that he is seeing a native view and not a webview, in such scenario showing the "page could not be loaded" error is preposterous. What I usually do in such situation is I load blank page and show a toast message as below
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.e(TAG," Error occured while loading the web page at Url"+ failingUrl+"." +description);
view.loadUrl("about:blank");
Toast.makeText(App.getContext(), "Error occured, please check newtwork connectivity", Toast.LENGTH_SHORT).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
if ( params.build_deploy == '1' ) {
println "build_deploy ? ${params.build_deploy}"
jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
string(name:'environment', value: "${params.environment}"),
string(name:'branch_name', value: "${params.branch_name}"),
string(name:'service_name', value: "${params.service_name}"),
]
println jobB.getResult()
}
bless
associates a reference with a package.
It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).
The effect bless
-ing has is that it allows you to apply special syntax to the blessed reference.
For example, if a blessed reference is stored in $obj
(associated by bless
with package "Class"), then $obj->foo(@args)
will call a subroutine foo
and pass as first argument the reference $obj
followed by the rest of the arguments (@args
). The subroutine should be defined in package "Class". If there is no subroutine foo
in package "Class", a list of other packages (taken form the array @ISA
in the package "Class") will be searched and the first subroutine foo
found will be called.
To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"
SELECT news.id, users.username, news.title, news.date,
news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
<>
is the valid SQL according to the SQL-92 standard.
http://msdn.microsoft.com/en-us/library/aa276846(SQL.80).aspx
You can now use the library called angular-print
I would suggest to use ASIHTTPRequest
ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.
It is suitable performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The included ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.
Please note, that the original author discontinued with this project. See the followring post for reasons and alternatives: http://allseeing-i.com/%5Brequest_release%5D;
Personally I am a big fan of AFNetworking
In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.
So in my humble opinion this is a more complete example based on Greg's one:
<?php
class Hello
{
/**
* Construct won't be called inside this class and is uncallable from
* the outside. This prevents instantiating this class.
* This is by purpose, because we want a static class.
*/
private function __construct() {}
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
I use this:
<script language='javascript'>
var t;
function doLoad() {
t = setTimeout("window.close()",1000);
}
</script>
<script type="text/javascript">
function refreshAndClose() {
window.opener.location.reload(true);
window.close();
}
</script>
<body onbeforeunload="refreshAndClose();" onLoad='doLoad()''>
when the window closes it then refreshes the parent window.
Use this also
NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];
Note - Your NSMakeRange(start, end)
should be NSMakeRange(start, end- start)
;
This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.
The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.
If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.
For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.
Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.
The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.
I'm a lot of fun at parties, I know.
I had same issue.. Very strange issue.. My HTML was with space after title
> <title>
>
> <script>
Fixed, after removing space
> <title>
> <script>
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Because Submit
button is inside login_modal
so you need to use loginDialog
view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
One big and great approach is to load the module from a NgModuleFactory
, you can load a module inside another module by calling this:
constructor(private loader: NgModuleFactoryLoader, private injector: Injector) {}
loadModule(path: string) {
this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
const entryComponent = (<any>moduleFactory.moduleType).entry;
const moduleRef = moduleFactory.create(this.injector);
const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
this.lazyOutlet.createComponent(compFactory);
});
}
I got this from here.
You can now use scroll-margin-top, which is pretty widely adopted.
Simply add the following CSS to the element you want to scroll to:
.element {
scroll-margin-top: 2em;
}
DateTime.Now is what you're searching for...
I think this could work:
select
case when datepart(dw,[Date]) = 1 then 7 else DATEPART(DW,[Date])-1 end as WeekDay
By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.
The first read in your case is being done when Web API is binding your model, after that the Request.Content
will not return anything.
You can remove the contact
from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):
[HttpPut]
public HttpResponseMessage Put(int accountId)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
...
}
That should do the trick (assuming that accountId
is URL parameter so it will not be treated as content read).
I would suggest interested parties have a look at Maarten Balliauw's solution. I think it is very elegant.
In case the link dissapears, it's using the MultiButton
attribute applied to a controller action to indicate which button click that action should relate to.
This is how to retrieve a Column Name from a DataColumn:
MyDataTable.Columns(1).ColumnName
To get the name of all DataColumns within your DataTable:
Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
name(i) = column.ColumnName
i += 1
Next
References
Here is a pure Java
solution actually:
public static long getFreePhysicalMemory()
{
com.sun.management.OperatingSystemMXBean bean =
(com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
return bean.getFreePhysicalMemorySize();
}
My 2 cents on this: pytest will fail at chance if you are not using virtual environments. Sometimes it will just work, sometimes not.
Therefore, the solution is:
The code, using windows PowerShell:
pip uninstall pytest
python.exe -m venv my_env
.\my_env\Scripts\activate
(my_env) pip install -e .
(my_env) pip install pytest pytest-html pandas numpy
Then finally
(my_env) pytest --html="my_testing_report.html"
An example of setup.py, for pip install -e:
import setuptools
setuptools.setup(
name='my_package',
version='devel',
author='erickfis',
author_email='[email protected]',
description='My package',
long_description='My gooood package',
packages=setuptools.find_packages(),
classifiers=[
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
],
include_package_data=True
)
This jQuery plugin gives you a pre-made way of selection/caret manipulation.
if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):
count before dedupe:
df.count()
do the de-dupe (convert the column you are de-duping to string type):
from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))
df.drop_duplicates(subset=['colName']).count()
can use a sorted groupby to check to see that duplicates have been removed:
df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)
Hi we can extract the pdf files using Apache Tika
The Example is :
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
public class WebPagePdfExtractor {
public Map<String, Object> processRecord(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
Map<String, Object> map = new HashMap<String, Object>();
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream input = null;
if (entity != null) {
try {
input = entity.getContent();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
ParseContext parseContext = new ParseContext();
parser.parse(input, handler, metadata, parseContext);
map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
map.put("title", metadata.get(TikaCoreProperties.TITLE));
map.put("pageCount", metadata.get("xmpTPg:NPages"));
map.put("status_code", response.getStatusLine().getStatusCode() + "");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return map;
}
public static void main(String arg[]) {
WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
System.out.println(extractedMap.get("text"));
}
}
F1 → open Keyboard Shortcuts → search for 'Indent Line', and change keybinding to Tab.
Right click > "Change when expression" to editorHasSelection && editorTextFocus && !editorReadonly
It will allow you to indent line when something in that line is selected (multiple lines still work).
Don't know if it's the best way but I'd do this:
=A1 & TEXT(A2,"mm/dd/yyyy")
That should format your date into your desired string.
Edit: That funny number you saw is the number of days between December 31st 1899 and your date. That's how Excel stores dates.
I do a IIFE, something like that:
(() => init())();
this code will be executed immediately and invoke the init function.
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
I used a variant of Alex's - but needed to to convert the param appearing multiple times to an array. There seem to be many options. I didn't want rely on another library for something this simple. I suppose one of the other options posted here may be better - I adapted Alex's because of the straight forwardness.
parseQueryString = function() {
var str = window.location.search;
var objURL = {};
// local isArray - defer to underscore, as we are already using the lib
var isArray = _.isArray
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
if(objURL[ $1 ] && !isArray(objURL[ $1 ])){
// if there parameter occurs more than once, convert to an array on 2nd
var first = objURL[ $1 ]
objURL[ $1 ] = [first, $3]
} else if(objURL[ $1 ] && isArray(objURL[ $1 ])){
// if there parameter occurs more than once, add to array after 2nd
objURL[ $1 ].push($3)
}
else
{
// this is the first instance
objURL[ $1 ] = $3;
}
}
);
return objURL;
};
The limit is dependent on both the server and the client used (and if applicable, also the proxy the server or the client is using).
Most web servers have a limit of 8192 bytes (8 KB), which is usually configurable somewhere in the server configuration. As to the client side matter, the HTTP 1.1 specification even warns about this. Here's an extract of chapter 3.2.1:
Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.
The limit in Internet Explorer and Safari is about 2 KB, in Opera about 4 KB and in Firefox about 8 KB. We may thus assume that 8 KB is the maximum possible length and that 2 KB is a more affordable length to rely on at the server side and that 255 bytes is the safest length to assume that the entire URL will come in.
If the limit is exceeded in either the browser or the server, most will just truncate the characters outside the limit without any warning. Some servers however may send an HTTP 414 error.
If you need to send large data, then better use POST instead of GET. Its limit is much higher, but more dependent on the server used than the client. Usually up to around 2 GB is allowed by the average web server.
This is also configurable somewhere in the server settings. The average server will display a server-specific error/exception when the POST limit is exceeded, usually as an HTTP 500 error.
To resolve all conflicts with the version in a particular branch:
git diff --name-only --diff-filter=U | xargs git checkout ${branchName}
So, if you are already in the merging state, and you want to keep the master version of the conflicting files:
git diff --name-only --diff-filter=U | xargs git checkout master
JSON_UNESCAPED_UNICODE
was added in PHP 5.4 so it looks like you need upgrade your version of PHP to take advantage of it. 5.4 is not released yet though! :(
There is a 5.4 alpha release candidate on QA though if you want to play on your development machine.
I set the PHPRC variable and uncommented zend_extension=php_opcache.dll
in php.ini
and all works well.
As per the hibernate
docs here,
Connection connection()
Deprecated. (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use doWork(org.hibernate.jdbc.Work) ...
Use Hibernate Work API instead:
Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do whatever you need to do with the connection
}
});
The line $('#myTextBox').focus()
alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
You can try changing it to this:
If myTableData.Rows.Count > 0 Then
For i As Integer = 0 To myTableData.Rows.Count - 1
''Dim DataType() As String = myTableData.Rows(i).Item(1)
ListBox2.Items.Add(myTableData.Rows(i)(1))
Next
End If
Note: Your loop needs to be one less than the row count since it's a zero-based index.
you can use program like tcpview from sysinternal. I guess it can help you a lot on both monitoring and killing unwanted connection.