If you're using Win10 with Xampp server installed, then you can find the data folder in C:\xampp\mysql\data
Inside the data folder, each database has its own folder which in turn contains the .frm, .myi and .myd files which represent for a single table in the database.
If for instance, you created a database with the name: myschool and inside the database, you have three tables with the names:
Then, you will have for the Nursery table: nursery.frm, nursery.myi and nursery.myd. Same will go for the Primary and Secondary tables. Thus, in the I mentioned here, you will a total of 9 files inside the database folder named myschool.
You can then copy the database folder and use it in your new mysql installation data folder.
I hope this helps.
Best regards.
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
I used pandas to convert my numpy array or iseries to an dataframe then added and additional the additional column by key as 'prediction'. If you need dataframe converted back to a list then use values.tolist()
output=pd.DataFrame(X_test)
output['prediction']=y_pred
list=output.values.tolist()
If you are using Jupyter in anaconda, after conda update scikit-learn
in terminal, close anaconda and restart, otherwise the error will occur again.
Removing the data attribute data-toggle="dropdown"
and implementing the open/close of the dropdown can be a solution.
First by handling the click on the link to open/close the dropdown like this :
$('li.dropdown.mega-dropdown a').on('click', function (event) {
$(this).parent().toggleClass('open');
});
and then listening the clicks outside of the dropdown to close it like this :
$('body').on('click', function (e) {
if (!$('li.dropdown.mega-dropdown').is(e.target)
&& $('li.dropdown.mega-dropdown').has(e.target).length === 0
&& $('.open').has(e.target).length === 0
) {
$('li.dropdown.mega-dropdown').removeClass('open');
}
});
Here is the demo : http://jsfiddle.net/RomaLefrancois/hh81rhcm/2/
Here is something that might help. Use the root privileges. if you have .bin then simply add the execution permission to the bin file.
chmod a+x jdk*.bin
next step is to run the .bin file which is simply
./jdk*.bin in the location you want to install.
you are done.
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable
interface and add the following method to the class:
@Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar)
syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
just add .col-xs-12 to your responsive image. It's should work.
No permissions to access nor install easy_install
?
Then, you can create a python virtualenv
(https://pypi.python.org/pypi/virtualenv) and install the package from this virtual environment.
Executing 4 commands in the shell will be enough (insert current release like 16.1.0 for X.X.X):
$ curl --location --output virtualenv-X.X.X.tar.gz https://github.com/pypa/virtualenv/tarball/X.X.X
$ tar xvfz virtualenv-X.X.X.tar.gz
$ python pypa-virtualenv-YYYYYY/src/virtualenv.py my_new_env
$ . my_new_env/bin/activate
(my_new_env)$ pip install package_name
Source and more info: https://virtualenv.pypa.io/en/latest/installation/
Since none of them all worked for me (select2 4.0.3) is went the std select way.
for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
selectbox.remove(i);
Because the error you're getting is not related to an EditText
, then it's not related to your keyboard.
The errors you are getting are not a result of your code; you probably are testing on a Samsung device that has Samsung's TouchWiz.
I had the same errors, then I tested on a Nexus S (also by Samsung, but pure Android OS without TouchWiz) and I didn't get this error.
So, in your case, just ignore these errors while testing on a device! :)
Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI):
Easiest way to check if they are authenticated is Request.User.IsAuthenticated
I think (from memory)
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeDoing an static import of the GestureTypes and then using the valuesOf() method could make it look much cleaner:
enum GestureTypes{ROCK,PAPER,SCISSORS};
and
import static com.example.GestureTypes.*;
public class GestureFactory {
public static Gesture getInstance(final String gesture) {
if (ROCK == valueOf(gesture))
//do somthing
if (PAPER == valueOf(gesture))
//do somthing
}
}
You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
----------------------
<head>
<script type="text/javascript">
<%=YourScript %>
function functionname1(arg1,arg2){content}
</script>
</head>
public string YourScript = "";
public string functionname(arg)
{
if (condition)
{
YourScript = "functionname1(arg1,arg2);";
}
}
If each file in your program is first compiled to an object file, then the object files are linked together, you need extern
. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."
I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.
Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant
For Each vFile In colFiles
'file operation here or store file name/path in a string array for use later in the script
filepath(n) = vFile
filename = fso.GetFileName(vFile) 'If you want the filename without full path
n=n+1
Next vFile
'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).
I suggest split (not saying that the other answers are invalid, this is just another way to do it):
def findreplace(char, string):
return ''.join(string.split(char))
Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below
In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'
And the speed...
In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204
Not as fast as replace or translate, but ok.
Collection is a interface which is used to represent group of individual object as a single entity.
Collections is an utility class present in java.util. package to define several utility method (like sorting,searching ) for collection object.
I prefer the following so I can still use top interactively without having to look up the pids each time I run it:
top -p `pgrep process-name | tr "\\n" "," | sed 's/,$//'`
Of course if the processes change you'll have to re-run the command.
Explanation:
pgrep process-name
returns a list of process ids which are separated by newlinestr "\\n" ","
translates these newlines into commas, because top wants a comma-separated list of process idssed
is a stream editor, and sed 's/,$//'
is used here to remove the trailing commaTo fix cross-origin-requests issues in a Node JS application:
npm i cors
And simply add the lines below to the app.js
let cors = require('cors')
app.use(cors())
You have to use new operator here to instantiate. For example:
Contacts.add(new Data(name, address, contact));
Sometime only this helps:
View child = parent.findViewById(R.id.btnMoreText);
child.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View parent = (View) v.getParent();
parent.performClick();
}
});
Another variant, works not always:
child.setOnClickListener(null);
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
If you prefer a graphical user interface, you can use pgAdmin III (Linux/Windows/OS X). Simply right click on the table of your choice, then "backup". It will create a pg_dump
command for you.
I always fall back on this solution. Not too hack-ish and gets the job done.
EDIT: I should point out that you might achieve the effect you want with the following code (forgive the inline styles; they should be in a separate sheet). It seems that the default alignment on an image (baseline) will cause the text to align to the baseline; setting that to middle gets things to render nicely, at least in FireFox 3.
<div>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg" style="vertical-align: middle;" width="100px"/>_x000D_
<span style="vertical-align: middle;">Here is some text.</span>_x000D_
</div>
_x000D_
If you're using NumPy from the Anaconda distribution, then you can just do:
$ conda list | grep numpy
numpy 1.11.3 py35_0
This gives the Python
version as well.
numexpr
It gives lot of information as you can see below:
In [692]: import numexpr
In [693]: numexpr.print_versions()
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.6.2
NumPy version: 1.13.3
Python version: 3.6.3 |Anaconda custom (64-bit)|
(default, Oct 13 2017, 12:02:49)
[GCC 7.2.0]
Platform: linux-x86_64
AMD/Intel CPU? True
VML available? False
Number of threads used by default: 8 (out of 48 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
A DataSet
already contains DataTables
. You can just use:
DataTable firstTable = dataSet.Tables[0];
or by name:
DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:
using (SqlConnection conn = ...)
{
// Code here...
}
In your Component you can add .class to your host element if you would have some general styles that you want to apply.
export class MyComponent{
@HostBinding('class') classes = 'classA classB';
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
I had this issue when i was trying to debug my code , (in using Toggle inspector in my android phone and react development ) , I did this simple steps :
Header header = new Header();
Byte[] headerBytes = new Byte[Marshal.SizeOf(header)];
Marshal.Copy((IntPtr)(&header), headerBytes, 0, headerBytes.Length);
This should do the trick quickly, right?
Here is an awesome and precise explanation I found.
TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.
TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.
TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.
TIMESTAMP is 4 bytes and DATETIME is 8 bytes.
TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'
Also...
I can't get it to work on $.get()
because it has no complete
event.
I suggest to use $.ajax()
like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
Since this question has become a standard question for breaking into a particular loop, I would like to give my answer with example using Exception
.
Although there exists no label named breaking of loop in multipally looped construct, we can make use of User-defined Exceptions to break into a particular loop of our choice. Consider the following example where let us print all numbers upto 4 digits in base-6 numbering system:
class BreakLoop(Exception):
def __init__(self, counter):
Exception.__init__(self, 'Exception 1')
self.counter = counter
for counter1 in range(6): # Make it 1000
try:
thousand = counter1 * 1000
for counter2 in range(6): # Make it 100
try:
hundred = counter2 * 100
for counter3 in range(6): # Make it 10
try:
ten = counter3 * 10
for counter4 in range(6):
try:
unit = counter4
value = thousand + hundred + ten + unit
if unit == 4 :
raise BreakLoop(4) # Don't break from loop
if ten == 30:
raise BreakLoop(3) # Break into loop 3
if hundred == 500:
raise BreakLoop(2) # Break into loop 2
if thousand == 2000:
raise BreakLoop(1) # Break into loop 1
print('{:04d}'.format(value))
except BreakLoop as bl:
if bl.counter != 4:
raise bl
except BreakLoop as bl:
if bl.counter != 3:
raise bl
except BreakLoop as bl:
if bl.counter != 2:
raise bl
except BreakLoop as bl:
pass
When we print the output, we will never get any value whose unit place is with 4. In that case, we don't break from any loop as BreakLoop(4)
is raised and caught in same loop. Similarly, whenever ten place is having 3, we break into third loop using BreakLoop(3)
. Whenever hundred place is having 5, we break into second loop using BreakLoop(2)
and whenver the thousand place is having 2, we break into first loop using BreakLoop(1)
.
In short, raise your Exception (in-built or user defined) in the inner loops, and catch it in the loop from where you want to resume your control to. If you want to break from all loops, catch the Exception outside all the loops. (I have not shown this case in example).
I'm on Kali Linux. I had to remove the brew version of postgresql with
brew uninstall postgresql
sudo -u postgres psql
got me into root postgres
You can make your own sharing button using the LinkedIn ShareArticle URL, which can have the following parameters:
https://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}
You can find the documentation here, just choose "Customized URL" to see the details.
I have done it by easiest way:
Just take one RelativeLayout and put your child view in it, which you want to place at right side.
<LinearLayout
android:id="@+id/llMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f5f4f4"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="20dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="20dp">
<ImageView
android:id="@+id/ivOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/txtOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="Hiren"
android:textAppearance="@android:style/TextAppearance.Medium"
android:textColor="@android:color/black" />
<RelativeLayout
android:id="@+id/rlRight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right">
<ImageView
android:id="@+id/ivRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
</LinearLayout>
Hope it will help you.
I had the same problem in letsencrypt (certbot) and nginx,
ref: https://github.com/certbot/certbot/issues/5486
this error does not have a solution yet
so, a changed a cron for renew (putting a reload after renew) (using suggest from certbot)
-- in /etc/cron.d/certbot
from
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew
to
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --pre-hook "service nginx stop" --post-hook "service nginx start"
logs (short):
-- in /var/log/syslog
Jun 10 00:14:25 localhost systemd[1]: Starting Certbot...
Jun 10 00:14:38 localhost certbot[22222]: nginx: [error] open() "/run/nginx.pid$
Jun 10 00:14:41 localhost certbot[22222]: Hook command "nginx" returned error c$
Jun 10 00:14:41 localhost certbot[22222]: Error output from nginx:
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:443 $
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] bind() to 0.0.0.0:80 f$
Jun 10 00:14:41 localhost certbot[22222]: nginx: [emerg] still could not bind()
Jun 10 00:14:41 localhost systemd[1]: Started Certbot.
-- in /var/log/nginx/error.log
2018/06/10 00:14:27 [notice] 22233#22233: signal process started
2018/06/10 00:14:31 [notice] 22237#22237: signal process started
2018/06/10 00:14:33 [notice] 22240#22240: signal process started
2018/06/10 00:14:34 [notice] 22245#22245: signal process started
2018/06/10 00:14:38 [notice] 22255#22255: signal process started
2018/06/10 00:14:38 [error] 22255#22255: open() "/run/nginx.pid" failed (2: No $
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:443 failed (98: Addr$
2018/06/10 00:14:39 [emerg] 22261#22261: bind() to 0.0.0.0:80 failed (98: Addre$
2018/06/10 00:14:39 [emerg] 22261#22261: still could not bind()
A null
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null
pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception
.
In general, it's because something hasn't been initialized properly.
If you face this issue only in Chrome and in IE, for instance, everything is fine, then just enable checkbutton "Disable cache" in Dev Tools (F12 -> "Network" tab) and clear history in the last hour.
I had this problem and above solution worked for me.
Use getBBox function
var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);
There is a difference between them, continue
skips the loop's current iteration and executes the next iteration.pass
does nothing. It’s an empty statement placeholder.
I would rather give you an example, which will clarify this more better.
>>> for element in some_list:
... if element == 1:
... print "Pass executed"
... pass
... print element
...
0
Pass executed
1
2
>>> for element in some_list:
... if element == 1:
... print "Continue executed"
... continue
... print element
...
0
Continue executed
2
Old way, no longer works:
<link rel="image_src" href="http://yoururl/yourimage"/>
Reported new way, also does not work:
<meta property="og:image" content="http://yoururl/yourimage"/>
It randomly worked off and on during the first day I implemented it, hasn't worked at all since.
The Facebook linter page, a utility that inspects your page, reports that everything is correct and does display the thumbnail I selected... just that the share.php page itself doesn't seem to be functioning. Has to be a bug over at Facebook, one they apparently don't care to fix as every bug report regarding this issue I've seen in their system all say resolved or fixed.
Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...)
call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:
buildTypes {
release {
runProguard true
proguardFile 'proguard-android.txt'
}
}
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use something like - Context.getExternalCacheDirs() or Context.getExternalFilesDirs() or Context.getObbDirs(). They give application specific directories in all external storage devices where the application can store its files.
So something like this - Context.getExternalCacheDirs()[i].getParentFile().getParentFile().getParentFile().getParent() can get you the root path of external storage devices.
I know these commands are for a different purpose but other answers didn't work for me.
This link gave me good pointers - https://possiblemobile.com/2014/03/android-external-storage/
The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.
On other servers, where the same services are consumed, the certificates were configured as follows:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"
As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"
Once that change was made, all was well. Thanks to everyone who offered assistance.
You could use a namedtuple instead of a dict. This is a shorthand for using a data class. Instead of
person = {'name': 'John', 'age': 14}
...do:
from collections import namedtuple
Person = namedtuple('person', ['name', 'age'])
p = Person(name='John', age=14)
p.name # 'John'
This is the same as writing a class that just holds data. In general I would avoid using dicts in django templates because they are awkward.
I usually use numpy sum over the logical condition column:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2
This seems to me slightly shorter than the solution presented above
Building off of @Karl Rosaen
parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()
and this outputs:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
We have Collection as below:
Syntax:
{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}
Example:
{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}
-OR-
Syntax:
ng-bind="(input | filter)"
Example:
ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"
I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.
Here's the mysql reference for cursors. So I'm guessing it's something like this:
DECLARE done INT DEFAULT 0;
DECLARE products_id INT;
DECLARE result varchar(4000);
DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO products_id;
IF NOT done THEN
CALL generate_parameter_list(@product_id, @result);
SET param = param + "," + result; -- not sure on this syntax
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
-- now trim off the trailing , if desired
Anything wrong with a one-liner?
$ perl -pi.bak -e 's/blue/red/g' *_classification.dat
Explanation
-p
processes, then prints <>
line by line-i
activates in-place editing. Files are backed up using the .bak
extensionUse user.dir
key for get project location using java.
Code:
System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));
OutPut:
Present Project Directory :C:\workspace\MyEclipse 10\examples\MySqlMavenDomain
For displaying all systems properties simply use System.getProperties();
Use Key
value in System.getProperty("java.version");
for get output.
Code:
Properties properties = System.getProperties();
Enumeration<Object> enumeration = properties.keys();
for (int i = 0; i < properties.size(); i++) {
Object obj = enumeration.nextElement();
System.out.println("Key: "+obj+"\tOutPut= "+System.getProperty(obj.toString()));
}
OutPut:
Key: java.runtime.name OutPut= Java(TM) SE Runtime Environment
Key: sun.boot.library.path OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\bin
Key: java.vm.version OutPut= 24.45-b08
Key: java.vm.vendor OutPut= Oracle Corporation
Key: java.vendor.url OutPut= http://java.oracle.com/
Key: path.separator OutPut= ;
Key: java.vm.name OutPut= Java HotSpot(TM) Client VM
Key: file.encoding.pkg OutPut= sun.io
Key: user.country OutPut= US
Key: user.script OutPut=
Key: sun.java.launcher OutPut= SUN_STANDARD
Key: sun.os.patch.level OutPut= Service Pack 3
Key: java.vm.specification.name OutPut= Java Virtual Machine Specification
Key: user.dir OutPut= C:\workspace\MyEclipse 10\examples\MySqlMavenDomain
Key: java.runtime.version OutPut= 1.7.0_45-b18
Key: java.awt.graphicsenv OutPut= sun.awt.Win32GraphicsEnvironment
Key: java.endorsed.dirs OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\endorsed
Key: os.arch OutPut= x86
Key: java.io.tmpdir OutPut= C:\DOCUME~1\UDAYP~2.PBS\LOCALS~1\Temp\
Key: line.separator OutPut=
Key: java.vm.specification.vendor OutPut= Oracle Corporation
Key: user.variant OutPut=
Key: os.name OutPut= Windows XP
Key: sun.jnu.encoding OutPut= Cp1252
Key: java.library.path OutPut= C:\Program Files\Java\jdk1.7.0_45\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin/client;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/lib/i386;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;D:\Program Files\Microsoft SQL Server\100\Tools\Binn\;D:\Program Files\Microsoft SQL Server\100\DTS\Binn\;.
Key: java.specification.name OutPut= Java Platform API Specification
Key: java.class.version OutPut= 51.0
Key: sun.management.compiler OutPut= HotSpot Client Compiler
Key: os.version OutPut= 5.1
Key: user.home OutPut= C:\Documents and Settings\uday.p.PBSYSTEMS
Key: user.timezone OutPut=
Key: java.awt.printerjob OutPut= sun.awt.windows.WPrinterJob
Key: file.encoding OutPut= UTF-8
Key: java.specification.version OutPut= 1.7
Key: java.class.path OutPut= C:\workspace\MyEclipse 10\examples\MySqlMavenDomain\target\test-classes;C:\workspace\MyEclipse 10\examples\MySqlMavenDomain\target\classes;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\jstl\jstl\1.2\jstl-1.2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\servlet\javax.servlet-api\3.1.0\javax.servlet-api-3.1.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\mysql\mysql-connector-java\5.1.28\mysql-connector-java-5.1.28.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\mail\mail\1.4.7\mail-1.4.7.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\activation\activation\1.1\activation-1.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\junit\junit\4.11\junit-4.11.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\hibernate-core\4.3.0.Final\hibernate-core-4.3.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\logging\jboss-logging\3.1.3.GA\jboss-logging-3.1.3.GA.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\logging\jboss-logging-annotations\1.2.0.Beta1\jboss-logging-annotations-1.2.0.Beta1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.0.0.Final\jboss-transaction-api_1.2_spec-1.0.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\xml-apis\xml-apis\1.0.b2\xml-apis-1.0.b2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\common\hibernate-commons-annotations\4.0.4.Final\hibernate-commons-annotations-4.0.4.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.0.Final\hibernate-jpa-2.1-api-1.0.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\jandex\1.1.0.Final\jandex-1.1.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\hibernate-entitymanager\4.3.0.Final\hibernate-entitymanager-4.3.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-dbcp\commons-dbcp\1.4\commons-dbcp-1.4.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-fileupload\commons-fileupload\1.3\commons-fileupload-1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-io\commons-io\2.4\commons-io-2.4.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-net\commons-net\3.3\commons-net-3.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-pool\commons-pool\1.6\commons-pool-1.6.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-beanutils\commons-beanutils\1.9.0\commons-beanutils-1.9.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\apache\commons\commons-lang3\3.1\commons-lang3-3.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\log4j\log4j\1.2.16\log4j-1.2.16.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-orm\3.2.6.RELEASE\spring-orm-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-jdbc\3.2.6.RELEASE\spring-jdbc-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-tx\3.2.6.RELEASE\spring-tx-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-web\3.2.6.RELEASE\spring-web-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-aop\3.2.6.RELEASE\spring-aop-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-webmvc\3.2.6.RELEASE\spring-webmvc-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-aspects\3.2.6.RELEASE\spring-aspects-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\aspectj\aspectjweaver\1.7.2\aspectjweaver-1.7.2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-beans\3.2.6.RELEASE\spring-beans-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-context\3.2.6.RELEASE\spring-context-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-context-support\3.2.6.RELEASE\spring-context-support-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-core\3.2.6.RELEASE\spring-core-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-expression\3.2.6.RELEASE\spring-expression-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-instrument\3.2.6.RELEASE\spring-instrument-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-instrument-tomcat\3.2.6.RELEASE\spring-instrument-tomcat-3.2.6.RELEASE.jar
Key: user.name OutPut= uday.p
Key: java.vm.specification.version OutPut= 1.7
Key: sun.java.command OutPut= com.uk.mysqlmaven.domain.test.UserLoginDetails
Key: java.home OutPut= C:\Program Files\Java\jdk1.7.0_45\jre
Key: sun.arch.data.model OutPut= 32
Key: user.language OutPut= en
Key: java.specification.vendor OutPut= Oracle Corporation
Key: awt.toolkit OutPut= sun.awt.windows.WToolkit
Key: java.vm.info OutPut= mixed mode, sharing
Key: java.version OutPut= 1.7.0_45
Key: java.ext.dirs OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
Key: sun.boot.class.path OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.7.0_45\jre\classes
Key: java.vendor OutPut= Oracle Corporation
Key: file.separator OutPut= \
Key: java.vendor.url.bug OutPut= http://bugreport.sun.com/bugreport/
Key: sun.io.unicode.encoding OutPut= UnicodeLittle
Key: sun.cpu.endian OutPut= little
Key: sun.desktop OutPut= windows
Key: sun.cpu.isalist OutPut= pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86
For more details refer Class System
import unicodedata
from random import choice
import perfplot
import regex
import text_unidecode
def remove_accent_chars_regex(x: str):
return regex.sub(r'\p{Mn}', '', unicodedata.normalize('NFKD', x))
def remove_accent_chars_join(x: str):
# answer by MiniQuark
# https://stackoverflow.com/a/517974/7966259
return u"".join([c for c in unicodedata.normalize('NFKD', x) if not unicodedata.combining(c)])
perfplot.show(
setup=lambda n: ''.join([choice('Málaga François Phút Hon ??') for i in range(n)]),
kernels=[
remove_accent_chars_regex,
remove_accent_chars_join,
text_unidecode.unidecode,
],
labels=['regex', 'join', 'unidecode'],
n_range=[2 ** k for k in range(22)],
equality_check=None, relative_to=0, xlabel='str len'
)
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
Loop through the results and place each one in an array
use mysqli_fetch_all()
to get them all at one time
from __future__ import division
somelist = [1,12,2,53,23,6,17]
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)
If you want to manually find the minimum as a function:
somelist = [1,12,2,53,23,6,17]
def my_min_function(somelist):
min_value = None
for value in somelist:
if not min_value:
min_value = value
elif value < min_value:
min_value = value
return min_value
Python 3.4 introduced the statistics
package, which provides mean
and additional stats:
from statistics import mean, median
somelist = [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)
* Answer may only be applicable to MacOS *
When trying to import a .sql file into a docker container, I encountered the error message:
Access denied; you need (at least one of) the SUPER privilege(s) for this operation
Then while trying some of the other suggestions, I received the below error on my MacOS (osx)
sed: RE error: illegal byte sequence
Finally, the following command from this resource resolved my "Access Denied" issue.
LC_ALL=C sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' fileName.sql
So I could import into the docker database with:
docker exec -i dockerContainerName mysql -uuser -ppassword table < importFile.sql
Hope this helps! :)
NuGet references
Assume the -Project_A (produces project_a.dll) -Project_B (produces project_b.dll) and Project_B references to Project_A by NuGet packages then just copy project_a.dll , project_a.pdb to the folder Project_B/Packages. In effect that should be copied to the /bin.
Now debug Project_A. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.
Do not use the ToList()
method as in the accepted answer !
Running SQL profiler, I verified and found that ToList()
function gets all the records from the database. It is really bad performance !!
I would have run this query by pure sql command as follows:
string query = "Update YourTable Set ... Where ...";
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));
This would operate the update in one-shot without selecting even one row.
npm i html-react-parser;
import Parser from 'html-react-parser';
<td>{Parser(this.state.archyves)}</td>
I would like to build on the answer given by @omeralper , which in my opinion provided a good foundation for a solid solution.
What I am proposing is a simplified and up to date version with the latest web standards. It is important to note that event.keycode is removed from the web standards, and future browser updates might not support it anymore. See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
Furthermore, the method
String.fromCharCode(e.keyCode);
does not guarantee that the keyCode pertaining to the key being pressed by the user maps to the expected letter as identified on the user's keyboard, since different keyboard configurations will result in a particular keycode different characters. Using this will introduce bugs which are difficult to identify, and can easily break the functionality for certain users. Rather I'm proposing the use of event.key, see docs here https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
Furthermore, we only want that the resultant output is a valid decimal. This means that the numbers 1, 11.2, 5000.2341234 should be accepted, but the value 1.1.2 should not be accepted.
Note that in my solution i'm excluding cut, copy and paste functionality since it open windows for bugs, especially when people paste unwanted text in associated fields. That would required a cleanup process on a keyup handler; which isn't the scope of this thread.
Here is the solution i'm proposing.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[myNumberOnly]'
})
export class NumberOnlyDirective {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home' ];
constructor(private el: ElementRef) {
}
@HostListener('keydown', [ '$event' ])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
If you are using the default theme. Just goto Preferences-> Default File Preferences A new tab pops up. At about line number you could see the font [font-name] [font-size]
Edit the font-size according to your wish and save.
Adding to the knowledge base, I got the same error for
if(class_iter->num == *int_iter)
Even though the IDE gave me the correct members for class_iter. Obviously, the problem is that "anything"::iterator
doesn't have a member called num
so I need to dereference it. Which doesn't work like this:
if(*class_iter->num == *int_iter)
...apparently. I eventually solved it with this:
if((*class_iter)->num == *int_iter)
I hope this helps someone who runs across this question the way I did.
Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.
It should probably be something like freq[Global.iParameter[2]-1]=false;
You would need to loop through the array to initialize all of it, this line only initializes the last element.
Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.
Best Regards
String.format("Hello %s Please find attached %s which is due on %s", name, invoice, date)
You can do something like this, without using any external libraries.
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.txt");
https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
var stream = response.pipe(file);
stream.on("finish", function() {
console.log("done");
});
});
In Terminal, enter the following:
# Set git to use the credential memory cache
git config --global credential.helper cache
By default, Git will cache your password for 15 minutes.
To change the default password cache timeout, enter the following:
# Set the cache to timeout after 1 hour (setting is in seconds)
git config --global credential.helper 'cache --timeout=3600'
From GitHub Help
You can write it globally like below.
Normal JS:
$(function(){
$('#loader').hide()
$(document).ajaxStart(function() {
$('#loader').show();
})
$(document).ajaxError(function() {
alert("Something went wrong...")
$('#loader').hide();
})
$(document).ajaxStop(function() {
$('#loader').hide();
});
$.ajaxSetup({
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}
});
});
Coffee Script:
$('#loader').hide()
$(document).ajaxStart ->
$('#loader').show()
$(document).ajaxError ->
alert("Something went wrong...")
$('#loader').hide()
$(document).ajaxStop ->
$('#loader').hide()
$.ajaxSetup {
beforeSend: (xhr) ->
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
}
You could simply use ^[\w.]+
to match A-Z, a-z, 0-9 and _
I faced same problem. Actually i face it often. Following three steps work for me always
Thants all. Now you can submit app using both application loader and Xcode.
Use arrow function:
Request.prototype.start = () => {
if( this.stay_open == true ) {
this.open({msg: 'listen'});
} else {
}
};
It defines an XML Namespace.
In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"
In the document, you see elements like: <android:foo />
Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo />
with regards to what it "means" when an XML parser reads the document.
NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.
Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/
Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.
So I put an special sub to declare global variables and arrays, something like:
Global example(10) As Variant
Sub set_values()
example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1
End Sub
And whenever I want to use the array, I call the sub first, just in case
call set_values
Msgbox example(5)
Perhaps is not the most correct way, but I hope it works for you
stdout is the standard output file stream. Obviously, it's first and default pointer to output is the screen, however you can point it to a file as desired!
Please read:
http://www.cplusplus.com/reference/cstdio/stdout/
C++ is very similar to C however, object oriented.
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
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!
?>
Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')
My issue was caused by missing bindings in IIS, in the left tree view "Connections", under Sites, Right click on your site > edit bindings > add > https
Choose 'IIS Express Development Certificate' and set port to 443 Then I added another binding to the webconfig:
<endpoint address="wsHttps" binding="wsHttpBinding" bindingConfiguration="DefaultWsHttpBinding" name="Your.bindingname" contract="Your.contract" />
Also added to serviceBehaviours:
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
And eventually it worked, none of the solutions I checked on stackoverflow for this error was applicable to my specific scenario, so including here in case it helps others
You can add header "Content-Type: text/html; charset=UTF-8" to your message body.
$headers = "Content-Type: text/html; charset=UTF-8";
If you use native mail()
function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)
If you user PEAR Mail::factory() code will be:
$smtp = Mail::factory('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
For me the following seemed to work.
git pull --tags
Another approach instead of saving the file on the server and retrieving it, is to use .NET 4.0+ ObjectCache with a short expiration until the second Action (at which time it can be definitively dumped). The reason that I want to use JQuery Ajax to do the call, is that it is asynchronous. Building my dynamic PDF file takes quite a bit of time, and I display a busy spinner dialog during that time (it also allows other work to be done). The approach of using the data returned in the "success:" to create a Blob does not work reliably. It depends on the content of the PDF file. It is easily corrupted by data in the response, if it is not completely textual which is all that Ajax can handle.
I was also facing same kind of problem on my Macbook Pro. I took these very simple steps and freshly installed Android Studio.
** Link Contains Images, look if facing any problem.
These Very Simple Steps Can Solve Your Problem.
This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.
It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.
Read more in Scott Hanselman's blog post about it and other VS improvements here.
As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:
The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.
this is how you do it if you want to listen for the "Enter" key. There is an onKeydown prop that you can use and you can read about it in react doc
and here is a codeSandbox
const App = () => {
const something=(event)=> {
if (event.keyCode === 13) {
console.log('enter')
}
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input type='text' onKeyDown={(e) => something(e) }/>
</div>
);
}
When working on a supercomputer, I received this error when I ran:
module load python/3.4.0
screen
python
To resolve the error, I simply needed to reload the module in the screen terminal:
module load python/3.4.0
python
How it Reduces the Performance of your application....? Read Following.
In Java Language Specification the Default / Initial Value for any Object can be given as Follows.
For type byte, the default value is zero, that is, the value of (byte) is 0.
For type short, the default value is zero, that is, the value of (short) is 0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types, the default value is null.
By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.
Because An array is a container object that holds a fixed number of values of a single type. Now the Type of array for you is int so consider the default value for all array elements will be automatically 0 Because it is holding int type.
Now consider the array for String type so that all array elements has default value is null.
Why don't do that......?
you can assign null value by using loop as you suggest in your Question.
int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
arr[i] = 0;
But if you do so then it will an useless loss of machine cycle. and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.
The more use of machine cycle ==> More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).
Update to Android Studio 3.0.1 which treats these as warnings. Android 3.0 was treating such warnings as errors and hence causing the gradle sync operation to fail.
You have to open database connection, not workbench file with schema. It looks a bit wierd, but it makes sense when you realize what you are editing.
So, go to home tab, double click database connection (create it if you don't have it yet) and have fun.
I think this is what you are looking for -
select Address1+Address2 as CompleteAddress from YourTable
where Address1+Address2 like '%YourSearchString%'
To prevent a compound word being created when we append address1 with address2, you can use this -
select Address1 + ' ' + Address2 as CompleteAddress from YourTable
where Address1 + ' ' + Address2 like '%YourSearchString%'
So, '123 Center St' and 'Apt 3B' will not be '123 Center StApt 3B' but will be '123 Center St Apt 3B'.
In my case, I was running npm install
from within a Docker container that was running the node:10.16.0-alpine
image. The problem was triggered by package.json
pointing at a package directly in GitHub:
"dependencies": {
"gulp-sass-inline-svg": "git+https://github.com/chriswburke/gulp-sass-inline-svg.git"
}
After switching to a Docker image that had git installed, the error went away.
On my mac the shortcut is ?cmd + / which makes multi line comment but as single lines:
// if ($username && $password) {
// echo "You are good to go";
// } else {
// echo "Fields cannot be blank";
// }
OR
? alt + ?cmd + / and it's result is overall comment, from beggining of the selection to the end.
/*
if ($username && $password) {
echo "You are good to go";
} else {
echo "Fields cannot be blank";
}
*/
You need to use the target
selector.
Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/
If you are running on a 64 bit system and trying to load a 32 bit dll you need to compile your application as 32 bit instead of any cpu. If you are not doing this it behaves exactly as you describe.
If that isn't the case use Dependency Walker to verify that the dll has its required dependencies.
I think you want to config your database server firstly after the installation, as shown in picture, you can reconfigure MySql server
If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.
switch(yourString)
{
case "john":
//do something for john
case "mary":
//do something for mary
}
The problem is with Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
this line. The Class qualified name is wrong
It is sqlserver.jdbc
not jdbc.sqlserver
Another way to do this:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
ul {
width: auto;
display: table;
margin-left: auto;
margin-right: auto;
}
ul li {
float: left;
list-style: none;
margin-right: 1rem;
}
The problem is how 100% height is being calculated. Two ways to deal with this.
Add 20px to the body padding-bottom
body {
padding-bottom: 20px;
}
or add a transparent border to body
body {
border: 1px solid transparent;
}
Both worked for me in firebug
Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.
Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.
Thirtydot's answer is completely legit. The p
around the script
is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.
But why? Shouldn't the p
tag's height, padding and margin be calculated into the height of the body?
And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p
space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.
The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.
In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.
Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.
My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.
xcode-select --install
worked for me
Just try this ..
function handleValueChange() {
var y = document.getElementById('textbox_id').value;
var x = document.getElementById('result');
x.innerHTML = y;
}
function changeTextarea() {
var a = document.getElementById('text-area').value;
var b = document.getElementById('text-area-result');
b.innerHTML = a;
}
_x000D_
input {
padding: 5px;
}
p {
white-space: pre;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
_x000D_
If the compiler can do automatic type inferencing, then there wont be any issue with performance. Both of these will generate same code
var x = new ClassA();
ClassA x = new ClassA();
however, if you are constructing the type dynamically (LINQ ...) then var
is your only question and there is other mechanism to compare to in order to say what is the penalty.
ApacheCommons surprised me,
StringUtils.abbreviate(String str, int maxWidth)
appends "..." there is no option to change postfix.
WordUtils.abbreviate(String str, int lower, int upper, String appendToEnd)
looks up to next empty space.
I’m just going to leave this here:
public static String abbreviate(String s, int maxLength, String appendToEnd) {
String result = s;
appendToEnd = appendToEnd == null ? "" : appendToEnd;
if (maxLength >= appendToEnd.length()) {
if (s.length()>maxLength) {
result = s.substring(0, Math.min(s.length(), maxLength - appendToEnd.length())) + appendToEnd;
}
} else {
throw new StringIndexOutOfBoundsException("maxLength can not be smaller than appendToEnd parameter length.");
}
return result;
}
I stumbled upon this problem again. But this time it occurred for a different reason. I had copied files into the repo to overwrite the previous versions. Now I can see the files are modified but diff doesn't return the diffs.
For example, I have a mainpage.xaml file.
In File Explorer I pasted a new mainpage.xaml file over the one in my current repo.
I did the work on another machine and just pasted the file here.
The file shows modified, but when I run git diff, it will not show the changes. It's probably because the fileinfo on the file has changed and git knows that it isn't really the same file. Interesting.
You can see that when I run diff on the file it shows nothing, just returns the prompt.
This is the way it worked for me:
$.post("/Controller/Action", $("#form").serialize(), function(json) {
// handle response
}, "json");
[HttpPost]
public ActionResult TV(MyModel id)
{
return Json(new { success = true });
}
/// <summary>
/// Validates the email if it follows the valid email format
/// </summary>
/// <param name="emailAddress"></param>
/// <returns></returns>
public static bool EmailIsValid(string emailAddress)
{
//if string is not null and empty then check for email follow the format
return string.IsNullOrEmpty(emailAddress)?false : new Regex(@"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", RegexOptions.IgnoreCase).IsMatch(emailAddress);
}
There are several ROT13 utilities written in Python on the 'Net -- just google for them. ROT13 encode the string offline, copy it into the source, decode at point of transmission.
But this is really weak protection...
Conceptually, arrays in JavaScript contain array.length
elements, starting with array[0]
up until array[array.length - 1]
. An array element with index i
is defined to be part of the array if i
is between 0
and array.length - 1
inclusive. If i is not in this range it's not in the array.
So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use
if (i >= 0 && i < array.length) {
// it is in array
}
Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length
n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.
What you probably want, however, is to know if a value in an array is actually something defined - that is, it's not undefined
. Maybe you even want to know if it's defined and not null
. It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.length
property, any new values will be undefined
.
To determine if a given value is something meaningful, or has been defined. That is, not undefined
, or null
:
if (typeof array[index] !== 'undefined') {
or
if (typeof array[index] !== 'undefined' && array[index] !== null) {
Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:
if (array[index] != null) {
// The == and != operators consider null equal to only null or undefined
}
int[] arr = {1, 2, 3};
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
int max_ = Collections.max(list);
int i;
if (max_ > 0) {
for (i = 1; i < Collections.max(list); i++) {
if (!list.contains(i)) {
System.out.println(i);
break;
}
}
if(i==max_){
System.out.println(i+1);
}
} else {
System.out.println("1");
}
}
If you don't do anything in your bash script than run the php one, you could simply run the php script from cron with a command like /usr/bin/php /path/to/your/file.php.
To support SDK version >= 26, you also should build NotificationChanel and set a vibration pattern and sound there. There is a Kotlin code sample:
val vibrationPattern = longArrayOf(500)
val soundUri = "<your sound uri>"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val attr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel =
NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.setSound(soundUri, attr)
notificationChannel.vibrationPattern = vibrationPattern
notificationManager.createNotificationChannel(notificationChannel)
}
And this is the builder:
with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
setContentTitle("Some title")
setContentText("Some content")
setSmallIcon(R.drawable.ic_logo)
setAutoCancel(true)
setVibrate(vibrationPattern)
setSound(soundUri)
setDefaults(Notification.DEFAULT_VIBRATE)
setContentIntent(
// this is an extension function of context you should build
// your own pending intent and place it here
createNotificationPendingIntent(
Intent(applicationContext, target).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
)
)
return build()
}
Be sure your AudioAttributes
are chosen right to read more here.
Using the for...in
loop for an array is not wrong, although I can guess why someone told you that:
1.) There is already a higher order function, or method, that has that purpose for an array, but has more functionality and leaner syntax, called 'forEach': Array.prototype.forEach(function(element, index, array) {} );
2.) Arrays always have a length, but for...in
and forEach
do not execute a function for any value that is 'undefined'
, only for the indexes that have a value defined. So if you only assign one value, these loops will only execute a function once, but since an array is enumerated, it will always have a length up to the highest index that has a defined value, but that length could go unnoticed when using these loops.
3.) The standard for loop will execute a function as many times as you define in the parameters, and since an array is numbered, it makes more sense to define how many times you want to execute a function. Unlike the other loops, the for loop can then execute a function for every index in the array, whether the value is defined or not.
In essence, you can use any loop, but you should remember exactly how they work. Understand the conditions upon which the different loops reiterate, their separate functionalities, and realize they will be more or less appropriate for differing scenarios.
Also, it may be considered a better practice to use the forEach
method than the for...in
loop in general, because it is easier to write and has more functionality, so you may want to get in the habit of only using this method and standard for, but your call.
See below that the first two loops only execute the console.log statements once, while the standard for loop executes the function as many times as specified, in this case, array.length = 6.
var arr = [];
arr[5] = 'F';
for (var index in arr) {
console.log(index);
console.log(arr[index]);
console.log(arr)
}
// 5
// 'F'
// => (6) [undefined x 5, 6]
arr.forEach(function(element, index, arr) {
console.log(index);
console.log(element);
console.log(arr);
});
// 5
// 'F'
// => Array (6) [undefined x 5, 6]
for (var index = 0; index < arr.length; index++) {
console.log(index);
console.log(arr[index]);
console.log(arr);
};
// 0
// undefined
// => Array (6) [undefined x 5, 6]
// 1
// undefined
// => Array (6) [undefined x 5, 6]
// 2
// undefined
// => Array (6) [undefined x 5, 6]
// 3
// undefined
// => Array (6) [undefined x 5, 6]
// 4
// undefined
// => Array (6) [undefined x 5, 6]
// 5
// 'F'
// => Array (6) [undefined x 5, 6]
The <a>
nchor element is simply an anchor to or from some content. Originally the HTML specification allowed for named anchors (<a name="foo">
) and linked anchors (<a href="#foo">
).
The named anchor format is less commonly used, as the fragment identifier is now used to specify an [id]
attribute (although for backwards compatibility you can still specify [name]
attributes). An <a>
element without an [href]
attribute is still valid.
As far as semantics and styling is concerned, the <a>
element isn't a link (:link
) unless it has an [href]
attribute. A side-effect of this is that an <a>
element without [href]
won't be in the tabbing order by default.
The real question is whether the <a>
element alone is an appropriate representation of a <button>
. On a semantic level, there is a distinct difference between a link
and a button
.
A button is something that when clicked causes an action to occur.
A link is a button that causes a change in navigation in the current document. The navigation that occurs could be moving within the document in the case of fragment identifiers (#foo
) or moving to a new document in the case of urls (/bar
).
As links are a special type of button, they have often had their actions overridden to perform alternative functions. Continuing to use an anchor as a button is ok from a consistency standpoint, although it's not quite accurate semantically.
If you're concerned about the semantics and accessibility of using an <a>
element (or <span>
, or <div>
) as a button, you should add the following attributes:
<a role="button" tabindex="0" ...>...</a>
The button role tells the user that the particular element is being treated as a button as an override for whatever semantics the underlying element may have had.
For <span>
and <div>
elements, you may want to add JavaScript key listeners for Space or Enter to trigger the click
event. <a href>
and <button>
elements do this by default, but non-button elements do not. Sometimes it makes more sense to bind the click
trigger to a different key. For example, a "help" button in a web app might be bound to F1.
Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.
Paul Jakubik, Callback Implementations in C++.
you can get using key
value something like this :
var size = new Array("S", "M", "L", "XL", "XXL");
var color = new Array("Red", "Blue", "Green", "White", "Black");
var options = new Array(size, color);
var len = options.length;
for(var i = 0; i<len; i++)
{
for(var key in options[i])
{
alert(options[i][key])
}
}
see here : http://jsfiddle.net/8hmRk/8/
Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.
public enum Gender {
MALE,
FEMALE
}
If you want them to be more complex, you can add values to them like this.
public enum Gender {
MALE("Male", 0),
FEMALE("Female", 1);
private String stringValue;
private int intValue;
private Gender(String toString, int value) {
stringValue = toString;
intValue = value;
}
@Override
public String toString() {
return stringValue;
}
}
Then to use the enum, you would do something like this:
Gender me = Gender.MALE
A bit late to the party but still - I prefer using numpy where:
import numpy as np
df['First Season'] = np.where(df['First Season'] > 1990, 1, df['First Season'])
I think a better answer here is simply this:
mike@sleepycat:~? kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
As for the "significance" of 9... I would say there is probably none. According to The Linux Programming Interface(p 388):
Each signal is defined as a unique (small) integer, starting sequentially from 1. These integers are defined in with symbolic names of the form SIGxxxx . Since the actual numbers used for each signal vary across implementations, it is these symbolic names that are always used in programs.
I spent almost a day trying to figure out why I was getting this exception. After lots of struggle, this config worked perfectly (Kotlin):
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lomza.moviesroom.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="movies_csv_files" path="."/>
</paths>
Intent itself
fun goToFileIntent(context: Context, file: File): Intent {
val intent = Intent(Intent.ACTION_VIEW)
val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
val mimeType = context.contentResolver.getType(contentUri)
intent.setDataAndType(contentUri, mimeType)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
return intent
}
I explain the whole process here.
To facilitate svg editing you can use an intermediate function:
function getNode(n, v) {
n = document.createElementNS("http://www.w3.org/2000/svg", n);
for (var p in v)
n.setAttributeNS(null, p, v[p]);
return n
}
Now you can write:
svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );
Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):
function getNode(n, v) {_x000D_
n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
for (var p in v)_x000D_
n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.
And if you are using python 3.X, you may apply the sorted
function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.
# using *sort method*
mylist.sort(lambda x: x[1])
# using *sorted function*
sorted(mylist, key = lambda x: x[1])
Right I think I know what you mean so lets see....
<div id="con">
<div id="content">Results will go here</div>
<div id="footer">Footer will always be at the bottom</div>
</div>
html,
body {
margin:0;
padding:0;
height:100%;
}
div {
outline: 1px solid;
}
#con {
min-height:100%;
position:relative;
}
#content {
height: 1000px; /* Changed this height */
padding-bottom:60px;
}
#footer {
position:absolute;
bottom:0;
width:100%;
height:60px;
}
This demo have the height of contentheight: 1000px;
so you can see what it would look like scrolling down the bottom.
This demo has the height of content height: 100px;
so you can see what it would look like with no scrolling.
So this will move the footer below the div content
but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.
Updated fiddles so its easier to see with backgrounds.
File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums
IN="[email protected];[email protected]"
IFS=';'
read -a IN_arr <<< "${IN}"
for entry in "${IN_arr[@]}"
do
echo $entry
done
Output
[email protected]
[email protected]
System : Ubuntu 12.04.1
I know already answered but who looking for 'Fri' like this
for Fri -
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
and who wants full date string they can use 4E for Friday
For Friday-
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Enjoy...
Like this:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
The $(this)
refers to the current .target
which will be looped through. Within this .target
I'm looking for the .scrolling img
and get the width. And then keep on going...
Images with different widths
If you want to calculate the width of all images (when they have different widths) you can do it like this:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.
In fact, i have such a setup myself.
To keep it basic, I used a loop and something like this to get you started (my index are datetimes):
import pandas as pd
import datetime as dt
#populate your dataframe: "df"
#...
df[df.index<(df.index[0]+dt.timedelta(hours=1))] #gives you a slice. you can then take .sum() .mean(), whatever
and then you can run functions on that slice. You can see how adding an iterator to make the start of the window something other than the first value in your dataframes index would then roll the window (you could use a > rule for the start as well for example).
Note, this may be less efficient for SUPER large data or very small increments as your slicing may become more strenuous (works for me well enough for hundreds of thousands of rows of data and several columns though for hourly windows across a few weeks)
Sadly, this is not possible by default to use section
as another user suggested, since a section
is only available to the immediate child
of a View
.
What works however is implementing and redefining the section
in every view, meaning:
section Head
{
@RenderSection("Head", false)
}
This way every view can implement a head section, not just the immediate children. This only works partly though, especially with multiple partials the troubles begin (as you have mentioned in your question).
So the only real solution to your problem is using the ViewBag
. The best would probably be a seperate collection (list) for CSS and scripts. For this to work, you need to ensure that the List
used is initialized before any of the views are executed. Then you can can do things like this in the top of every view/partial (without caring if the Scripts
or Styles
value is null:
ViewBag.Scripts.Add("myscript.js");
ViewBag.Styles.Add("mystyle.css");
In the layout you can then loop through the collections and add the styles based on the values in the List
.
@foreach (var script in ViewBag.Scripts)
{
<script type="text/javascript" src="@script"></script>
}
@foreach (var style in ViewBag.Styles)
{
<link href="@style" rel="stylesheet" type="text/css" />
}
I think it's ugly, but it's the only thing that works.
******UPDATE****
Since it starts executing the inner views first and working its way out to the layout and CSS styles are cascading, it would probably make sense to reverse the style list via ViewBag.Styles.Reverse()
.
This way the most outer style is added first, which is inline with how CSS style sheets work anyway.
To use CodeIgniter with jQuery Ajax, use "Object" as data instead of Query string as below:
$.ajax({
url: site_url + "ajax/signup",
data: ({'email': email, 'password': password}), //<--- Use Object
type: "post",
success: function(response, textStatus, jqXHR){
$('#sign-up').html(response);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("The following error occured: "+
textStatus, errorThrown);
}
});
Please try jQuery UI dialog
Here is the forms demo
For mobile use, have a look at jQuery Mobile - Creating dialogs
I think you could insert an image tag into a noscript tag and look at the stats how many times your site and how often this image has been loaded.
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
Doing type('')
is effectively equivalent to str
and types.StringType
so type('') == str == types.StringType
will evaluate to "True
"
Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode)
or assert isinstance(obj, basestring)
, the latter of which was suggested in the comments by 007Brendan and is probably preferred.
isinstance()
is useful if you want to ask whether an object is an instance of a class, e.g:
class MyClass: pass
print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception
But for basic types, e.g. str
, unicode
, int
, float
, long
etc asking type(var) == TYPE
will work OK.
The great thing about HTML/CSS is that there's usually more than one way to achieve the same effect. Here's another solution that does what you want:
<nav id="menu1">
<ul>
<li><a href="#">Menu Link 1</a></li>
<li><a href="#">Menu Link 2</a></li>
</ul>
</nav>
nav {
background:#666;
margin:1em;
padding:.5em 0;
}
nav ul {
border-top:1px dashed #fff;
list-style:none;
padding:.5em;
}
nav ul li {
display:inline-block;
}
nav ul li a {
color:#fff;
}
What could be easier than something like this:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
Using tempfile is a lot better than trying to reinvent it.
Instead of checking for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
as many answers suggest, there is a slightly simpler way -
Add the following line to the application
section of AndroidManifest.xml file as explained in the Set Up a Firebase Cloud Messaging Client App on Android doc:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
Then add a line with a channel name to the values/strings.xml file:
<string name="default_notification_channel_id">default</string>
After that you will be able to use the new version of NotificationCompat.Builder constructor with 2 parameters (since the old constructor with 1 parameter has been deprecated in Android Oreo):
private void sendNotification(String title, String body) {
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this,
0 /* Request code */,
i,
PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pi);
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
There's not really a good way to do this, usually you see an extra item in the enum, i.e.
enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};
So then you can do:
int fuz[FOOBAR_NR_ITEMS];
Still not very nice though.
But of course you do realize that just the number of items in an enum is not safe, given e.g.
enum foobar {foo, bar = 5, baz, quz = 20};
the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.
edit: as requested, made the special entry stick out more.
Try to look at Net2Java It seems to me the best option for automatic (or semi-automatic at least) conversion from C# to Java
This returns a numpy array:
arr = df["cluster"].to_numpy()
This returns a numpy array of unique values:
unique_arr = df["cluster"].unique()
You can also use numpy to get the unique values, although there are differences between the two methods:
arr = df["cluster"].to_numpy()
unique_arr = np.unique(arr)
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
you can just do
select rownum, l.* from student l where name like %ram%
this assigns the row number as the rows are fetched (so no guaranteed ordering of course).
if you wanted to order first do:
select rownum, l.*
from (select * from student l where name like %ram% order by...) l;
If you don't feel like importing anything, you can try:
raise SystemExit, 0
form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
or
form_for @user, :url => whatever_path
swift enforces you to initialise every member var before it is ever/might ever be used. Since it can't be sure what happens when it is supers turn, it errors out: better safe than sorry
Explanation: when you do a maven reimport, it will download all the missing plugins again.
Happy Coding
The easiest way to create daemon with Python is to use the Twisted event-driven framework. It handles all of the stuff necessary for daemonization for you. It uses the Reactor Pattern to handle concurrent requests.
Initialize the current cursor. Use it to get the position of X and Y
this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;
CASE-1
In the below code I navigated to 3 different URLs and when the execution comes to navigate command, it navigated back to facebook home page.
public class FirefoxInvoke {
@Test
public static void browserInvoke()
{
System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
WebDriver driver=new FirefoxDriver();
System.out.println("Before"+driver.getTitle());
driver.get("http://www.google.com");
driver.get("http://www.facebook.com");
driver.get("http://www.india.com");
driver.navigate().back();
driver.quit();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
browserInvoke();
}
}
CASE-2:
In below code, I have used navigate() instead of get(), but both the snippets(Case-1 and Case-2) are working exactly the same, just the case-2 execution time is less than of case-1
public class FirefoxInvoke {
@Test
public static void browserInvoke()
{
System.setProperty("webdriver.gecko.driver", "gecko-driver-path");
WebDriver driver=new FirefoxDriver();
System.out.println("Before"+driver.getTitle());
driver.navigate().to("http://www.google.com");
driver.navigate().to("http://www.facebook.com");
driver.navigate().to("http://www.india.com");
driver.navigate().back();
driver.quit();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
browserInvoke();
}
}
Python does let you use a semi-colon to denote the end of a statement if you are including more than one statement on a line.
In Laravel 5.5
I was trying to accomplish the same problem in Laravel 5.5. Instead of using Auth::routes()
in the web.php routes file, I only included the login/logout routes:
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
As of Spring Boot 1.3.0.M3
, the H2 console can be auto-configured.
The prerequisites are:
Even if you don't use Spring Boot Dev Tools, you can still auto-configure the console by setting spring.h2.console.enabled
to true
Check out this part of the documentation for all the details.
Note that when configuring in this way the console is accessible at: http://localhost:8080/h2-console/
Yes it is possible to do so. This worked out for me.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;
public static void readBashScript() {
try {
Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':
So, in my case, ended like this:
if __name__ == '__main__':
import librosa
import os
import pandas as pd
run_my_program()
If you want to filter out extensions from the output of another command e.g. "git":
files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')
for file in $files; do
echo "$file"
done
Thanks everyone especially szatmary as this is a complex question and has many layers to it, all which have to be working before you can stream live video. To clarify my original question and HTML5 video use vs flash - my use case has a strong preference for HTML5 because it is generic, easy to implement on the client and the future. Flash is a distant second best so lets stick with HTML5 for this question.
I learnt a lot through this exercise and agree live streaming is much harder than VOD (which works well with HTML5 video). But I did get this to work satisfactorily for my use case and the solution worked out to be very simple, after chasing down more complex options like MSE, flash, elaborate buffering schemes in Node. The problem was that FFMPEG was corrupting the fragmented MP4 and I had to tune the FFMPEG parameters, and the standard node stream pipe redirection over http that I used originally was all that was needed.
In MP4 there is a 'fragmentation' option that breaks the mp4 into much smaller fragments which has its own index and makes the mp4 live streaming option viable. But not possible to seek back into the stream (OK for my use case), and later versions of FFMPEG support fragmentation.
Note timing can be a problem, and with my solution I have a lag of between 2 and 6 seconds caused by a combination of the remuxing (effectively FFMPEG has to receive the live stream, remux it then send it to node for serving over HTTP). Not much can be done about this, however in Chrome the video does try to catch up as much as it can which makes the video a bit jumpy but more current than IE11 (my preferred client).
Rather than explaining how the code works in this post, check out the GIST with comments (the client code isn't included, it is a standard HTML5 video tag with the node http server address). GIST is here: https://gist.github.com/deandob/9240090
I have not been able to find similar examples of this use case, so I hope the above explanation and code helps others, especially as I have learnt so much from this site and still consider myself a beginner!
Although this is the answer to my specific question, I have selected szatmary's answer as the accepted one as it is the most comprehensive.
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
Remove Windows Service via Registry
Its very easy to remove a service from registry if you know the right path. Here is how I did that:
Run Regedit or Regedt32
Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"
Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).
Delete Windows Service via Command Window
Alternatively, you can also use command prompt and delete a service using following command:
sc delete
You can also create service by using following command
sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"
Note: You may have to reboot the system to get the list updated in service manager.
Here I am posting a piece of code that i use to add a new contact. It works fine for me. I hope it will help you.
String DisplayName = "XYZ";
String MobileNumber = "123456";
String HomeNumber = "1111";
String WorkNumber = "2222";
String emailID = "[email protected]";
String company = "bad";
String jobTitle = "abcd";
ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();
ops.add(ContentProviderOperation.newInsert(
ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
//------------------------------------------------------ Names
if (DisplayName != null) {
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
DisplayName).build());
}
//------------------------------------------------------ Mobile Number
if (MobileNumber != null) {
ops.add(ContentProviderOperation.
newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
}
//------------------------------------------------------ Home Numbers
if (HomeNumber != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
.build());
}
//------------------------------------------------------ Work Numbers
if (WorkNumber != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
.build());
}
//------------------------------------------------------ Email
if (emailID != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
}
//------------------------------------------------------ Organization
if (!company.equals("") && !jobTitle.equals("")) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
.build());
}
// Asking the Contact provider to create a new contact
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
Here is the code. Integrate it according to your need. I hope it will help.
If using Visual Code one option is to add this to the settings.json file:
"eslint.options": {
"useEslintrc": false,
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"es6": true
}
}
It is also possible to receive this error from a select component if the query fails in an unusual manner (eg: a sub-query returns multiple rows in an oracle oledb connection)
for counting:
$('.yourClass').length;
should work fine.
storing in a variable is as easy as:
var count = $('.yourClass').length;
This can be accomplished without javascript, with this metatag:
<meta http-equiv="refresh" content="5" >
where content ="5" are the seconds that the page will wait until refreshed.
But you said only if there was no activity, what kind for activity would that be?
in my case I was using below dependency
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.42</version>
</dependency>
and getting the same exception of Auth fail, but updated dependency to below version and problem get resolved.
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
You can use the fuser
command, like:
fuser file_name
You will receive a list of processes using the file.
You can use different flags with it, in order to receive a more detailed output.
You can find more info in the fuser's Wikipedia article, or in the man
pages.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:padding="10dp"
android:text="HELLO WORLD" />
</LinearLayout>
As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.
In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.minimumZoomScale = 0.5;
self.scrollView.maximumZoomScale = 6.0;
self.scrollView.contentSize = self.imageView.frame.size;
self.scrollView.delegate = self;
}
You are required to implement the following method to return the imageView you want to zoom.
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
In versions prior to iOS9, you may also need to add this empty delegate method:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}
The Apple Documentation does a good job of describing how to do this:
It can happen when server does not respond due to 100% CPU or Memory utilization.
I got this error when I was trying to access sonarqube API and the server was not responding due to full memory utilization
In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.
You want to check the result of scanf() to make sure there was a successful conversion; if there wasn't, then one of three things is true:
Example:
int moreData = 1;
...
printf("Input no: ");
fflush(stdout);
/**
* Loop while moreData is true
*/
while (moreData)
{
errno = 0;
int itemsRead = scanf("%f", &input);
if (itemsRead == 1)
{
printf("Output: %f\n", input);
printf("Input no: ");
fflush(stdout);
}
else
{
if (feof(stdin))
{
printf("Hit EOF on stdin; exiting\n");
moreData = 0;
}
else if (ferror(stdin))
{
/**
* I *think* scanf() sets errno; if not, replace
* the line below with a regular printf() and
* a generic "read error" message.
*/
perror("error during read");
moreData = 0;
}
else
{
printf("Bad character stuck in input stream; clearing to end of line\n");
while (getchar() != '\n')
; /* empty loop */
printf("Input no: ");
fflush(stdout);
}
}
Again with the inverting, you could simply use the following code:
for k,v in pairs(t) do
if not isstring(k) then
-- do something to t[k] when k is not a string
end
Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.
One way to get around this is to do something like this.
<c:set var="longKey" value="${param.selectedIndex + 0}"/>
This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.
Then, continue as usual with something like
${map[longKey]}
You can take a look at Shield UI's Switch widget. It is as easy to use as this:
<input id="switch3" type="checkbox" value="" />
<script>
jQuery(function ($) {
$("#switch3").shieldSwitch({
onText: "Yes, save it",
ffText: "No, delete it",
cls: "large"
});
});
</script>
It does not work because sequence does not work in following scenarios:
Source: http://www.orafaq.com/wiki/ORA-02287
However this does work:
insert into table_name
(col1, col2)
select my_seq.nextval, inner_view.*
from (select 'some value' someval
from dual
union all
select 'another value' someval
from dual) inner_view;
Try it out:
create table table_name(col1 varchar2(100), col2 varchar2(100));
create sequence vcert.my_seq
start with 1
increment by 1
minvalue 0;
select * from table_name;
Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:
For anyone finding this, swipe on carousel appears to be native as of about 5 days ago (20 Oct 2018) as per
https://github.com/twbs/bootstrap/pull/25776
https://deploy-preview-25776--twbs-bootstrap4.netlify.com/docs/4.1/components/carousel/
$("element").on("event1 event2 event..n", function() {
//execution
});
This tutorial is about handling multiple events.
These are some Extension methods that can help
public static bool IsInRange<T>(this T value, T min, T max)
where T : System.IComparable<T>
{
return value.IsGreaterThenOrEqualTo(min) && value.IsLessThenOrEqualTo(max);
}
public static bool IsLessThenOrEqualTo<T>(this T value, T other)
where T : System.IComparable<T>
{
var result = value.CompareTo(other);
return result == -1 || result == 0;
}
public static bool IsGreaterThenOrEqualTo<T>(this T value, T other)
where T : System.IComparable<T>
{
var result = value.CompareTo(other);
return result == 1 || result == 0;
}
If you're using Owl Carousel 2
, then you should use the following:
$(".category-wrapper").owlCarousel({
items : 4,
loop : true,
margin : 30,
nav : true,
smartSpeed :900,
navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]
});
In Summary:
conda list
(It will provide all the libraries along with version details).
And:
pip show tensorflow
(It gives complete library details).
another solution is the function you can embed into your own utils.py
import time as time_ #make sure we don't override time
def millis():
return int(round(time_.time() * 1000))
Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.
Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.
Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.
Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.
I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.
I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.
.inspect
is what you're looking for, it's way easier IMO than .to_yaml
!
user = User.new
user.name = "will"
user.email = "[email protected]"
user.inspect
#<name: "will", email: "[email protected]">
At least for pip 1.3.1, it honors the http_proxy and https_proxy environment variables. Make sure you define both, as it will access the PYPI index using https.
export https_proxy="http://<proxy.server>:<port>"
pip install TwitterApi
Like has been repeated, functors are classes that can be treated as functions (overload operator ()).
They are most useful for situations in which you need to associate some data with repeated or delayed calls to a function.
For example, a linked-list of functors could be used to implement a basic low-overhead synchronous coroutine system, a task dispatcher, or interruptable file parsing. Examples:
/* prints "this is a very simple and poorly used task queue" */
class Functor
{
public:
std::string output;
Functor(const std::string& out): output(out){}
operator()() const
{
std::cout << output << " ";
}
};
int main(int argc, char **argv)
{
std::list<Functor> taskQueue;
taskQueue.push_back(Functor("this"));
taskQueue.push_back(Functor("is a"));
taskQueue.push_back(Functor("very simple"));
taskQueue.push_back(Functor("and poorly used"));
taskQueue.push_back(Functor("task queue"));
for(std::list<Functor>::iterator it = taskQueue.begin();
it != taskQueue.end(); ++it)
{
*it();
}
return 0;
}
/* prints the value stored in "i", then asks you if you want to increment it */
int i;
bool should_increment;
int doSomeWork()
{
std::cout << "i = " << i << std::endl;
std::cout << "increment? (enter the number 1 to increment, 0 otherwise" << std::endl;
std::cin >> should_increment;
return 2;
}
void doSensitiveWork()
{
++i;
should_increment = false;
}
class BaseCoroutine
{
public:
BaseCoroutine(int stat): status(stat), waiting(false){}
void operator()(){ status = perform(); }
int getStatus() const { return status; }
protected:
int status;
bool waiting;
virtual int perform() = 0;
bool await_status(BaseCoroutine& other, int stat, int change)
{
if(!waiting)
{
waiting = true;
}
if(other.getStatus() == stat)
{
status = change;
waiting = false;
}
return !waiting;
}
}
class MyCoroutine1: public BaseCoroutine
{
public:
MyCoroutine1(BaseCoroutine& other): BaseCoroutine(1), partner(other){}
protected:
BaseCoroutine& partner;
virtual int perform()
{
if(getStatus() == 1)
return doSomeWork();
if(getStatus() == 2)
{
if(await_status(partner, 1))
return 1;
else if(i == 100)
return 0;
else
return 2;
}
}
};
class MyCoroutine2: public BaseCoroutine
{
public:
MyCoroutine2(bool& work_signal): BaseCoroutine(1), ready(work_signal) {}
protected:
bool& work_signal;
virtual int perform()
{
if(i == 100)
return 0;
if(work_signal)
{
doSensitiveWork();
return 2;
}
return 1;
}
};
int main()
{
std::list<BaseCoroutine* > coroutineList;
MyCoroutine2 *incrementer = new MyCoroutine2(should_increment);
MyCoroutine1 *printer = new MyCoroutine1(incrementer);
while(coroutineList.size())
{
for(std::list<BaseCoroutine *>::iterator it = coroutineList.begin();
it != coroutineList.end(); ++it)
{
*it();
if(*it.getStatus() == 0)
{
coroutineList.erase(it);
}
}
}
delete printer;
delete incrementer;
return 0;
}
Of course, these examples aren't that useful in themselves. They only show how functors can be useful, the functors themselves are very basic and inflexible and this makes them less useful than, for example, what boost provides.
Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10
all children parent_id's of 10 will also be updated to 20
If you don't update the field the foreign key refers to, this setting is not needed
Can't think of any other use.
You can't do that as the foreign key constraint would fail.
$("#myId").val()
should work if myid
is the select element id!
This would set the selected item: $("#myId").val('VALUE');