I had been facing this problem for two days and I found that the directory you create in Oracle also needs to created first on your physical disk.
I didn't find this point mentioned anywhere i tried to look up the solution to this.
If you created a directory, let's say, 'DB_DIR
'.
CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DB_WORKS';
Then you need to ensure that DB_WORKS
exists in your E:\
drive and also file system level Read/Write permissions are available to the Oracle process.
My understanding of UTL_FILE from my experiences is given below for this kind of operation.
UTL_FILE is an object under SYS user. GRANT EXECUTE ON SYS.UTL_FILE TO PUBLIC; needs to given while logged in as SYS. Otherwise, it will give declaration error in procedure. Anyone can create a directory as shown:- CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DBWORKS'; But CREATE DIRECTORY permission should be in place. This can be granted as shown:- GRANT CREATE ALL DIRECTORY TO user; while logged in as SYS user. However, if this needs to be used by another user, grants need to be given to that user otherwise it will throw error. GRANT READ, WRITE, EXECUTE ON DB_DIR TO user; while loggedin as the user who created the directory. Then, compile your package. Before executing the procedure, ensure that the Directory exists physically on your Disk. Otherwise it will throw 'Invalid File Operation' error. (V. IMPORTANT) Ensure that Filesystem level Read/Write permissions are in place for the Oracle process. This is separate from the DB level permissions granted.(V. IMPORTANT) Execute procedure. File should get populated with the result set of your query.
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
Here is a simple example:
ThreadTest.java
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 300);
MyThread t2 = new MyThread(1, 3, 300);
MyThread t3 = new MyThread(2, 3, 300);
t1.start();
t2.start();
t3.start();
}
}
MyThread.java
public class MyThread extends Thread
{
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m)
{
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run()
{
for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
{
System.out.println("[ID " + this.getId() + "] " + i);
}
}
}
And some output:
[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23
An explanation - Each MyThread
object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1
does index 0, 3, 6, 9, etc.
Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
I tried all the above and nothing worked for me. This solved all my problems:
pip install -U numpy
pip install -U scipy
Note that the -U
option to pip install
requests that the package be upgraded. Without it, if the package is already installed pip
will inform you of this and exit without doing anything.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):
CSS background transparency without affecting child elements, through RGBa and filters
From there you can add gradient support, etc.
Guava's Multimap is better suited for this. Here is a short clean version:
Multimap<String, String> getUrlParameters(String url) {
try {
Multimap<String, String> ret = ArrayListMultimap.create();
for (NameValuePair param : URLEncodedUtils.parse(new URI(url), "UTF-8")) {
ret.put(param.getName(), param.getValue());
}
return ret;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
It does not write to a file by default. You would need to configure something like the RollingFileAppender
and have the root logger write to it (possibly in addition to the default ConsoleAppender
).
In Laravel 5.1, this works in a Blade:
<?php
switch( $machine->disposal ) {
case 'DISPO': echo 'Send to Property Disposition'; break;
case 'UNIT': echo 'Send to Unit'; break;
case 'CASCADE': echo 'Cascade the machine'; break;
case 'TBD': echo 'To Be Determined (TBD)'; break;
}
?>
It looks like you're running this on Windows (given your H://log.txt
file path).
Try using \r\n
instead of just \n
.
Honestly, \n
is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).
I know this question was asked over 2 years ago but no one has mentioned this yet.
The best method is to use a http header
Adding the meta tag to the head doesn't always work because IE might have determined the mode before it's read. The best way to make sure IE always uses standards mode is to use a custom http header.
Header:
name: X-UA-Compatible
value: IE=edge
For example in a .NET application you could put this in the web.config file.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=edge" />
</customHeaders>
</httpProtocol>
</system.webServer>
Any of the following should work!!
df <- data.frame(x=1:3,y=4:6)
mean(df$x)
mean(df[,1])
mean(df[["x"]])
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
As for me, chaining set
methods is the cleanest way
const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");
You can define the PagerAdapter
like this then you will able to get any Fragment
in ViewPager
.
private class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
}
To get the current Fragment
Fragment currentFragment = mPagerAdapter.getItem(mViewPager.getCurrentItem());
None of the other answers worked for me. My workaround was to trigger a click on the video itself; hacky (because of the timeout that is needed) but it works fine:
function startVideoIfNotStarted () {
$(".id_of_video_tag").ready(function () {
window.setTimeout(function(){
videojs("id_of_video_tag").play()
}, 1000);
});
}
$(startVideoIfNotStarted);
Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes
or AxesSubplot
object. The functions of interest are set_autoscale_on
, set_autoscalex_on
, and set_autoscaley_on
.
In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on
property to False
. Here is a modified version of the FFT subplot snippet from your code:
fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))
To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:
<link rel="icon" href="_/img/favicon.png">
This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
.
To learn more about using other file types like PNG check out this question.
For cache busting purposes:
Add a query string to the path for cache-busting purposes:
<link rel="icon" href="/favicon.ico?v=1.1">
Favicons are very heavily cached and this a great way to ensure a refresh.
Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link
for it.
Footnote about rel="icon"
:
As indicated by @Semanino's answer, using rel="shortcut icon"
is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon"
instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel
value of shortcut
isn't a valid option.
theString.substring(theString.length() - 2)
SELECT NAME FROM v$database;
shows the database name in oracle
enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };
const char * getTextForEnum( int enumVal )
{
return EnumStrings[enumVal];
}
This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true
.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Thanks everyone!
onDestroyed()
is wrong name for
onDestroy()
Did you make a mistake only in this question or in your code too?
Try to use the following approach (it works for me):
@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")
List<String> findUsersWithPartOfName(@Param("username") String username);
Notice: The table name in JPQL must start with a capital letter.
It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.
If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.
You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)
in the AndroidManifest.xml file change the user-sdk to older version
<uses-sdk android:minSdkVersion="19"/>
I would not say it is a standard way to swap because it will cause some unexpected errors.
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
nums[i]
will be modified first and then affect the second variable nums[nums[i] - 1]
.
If we follow the w3 org table reference ,and follow the Permitted Contents section, we can see that the table
tags takes tbody
(optional) and tr
as the only permitted contents.
So i reckon it is safe to say we cannot add a div
tag which is a flow content as a direct child of the table
which i understand is what you meant when you had said above a tr
.
Having said that , as we follow the above link , you will find that it is safe to use div
s inside the td
element as seen here
You use the available API of JTable
and do not try to mess with the colors.
Some selection methods are available directly on the JTable
(like the setRowSelectionInterval
). If you want to have access to all selection-related logic, the selection model is the place to start looking
I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud
After that i restarted the VM. Then again changed the password and then it worked.
user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password:
Retype new password:
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password:
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #
there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.
Hoping this can help someone someday :)
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
*
* @author leBenj
*/
public class Array2DWeakRefsBuffered<T>
{
private final WeakReference<T>[][] _array;
private final Queue<T> _buffer;
private final int _width;
private final int _height;
private final int _bufferSize;
@SuppressWarnings( "unchecked" )
public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
{
_width = w;
_height = h;
_bufferSize = bufferSize;
_array = new WeakReference[_width][_height];
_buffer = new LinkedList<T>();
}
/**
* Tests the existence of the encapsulated object
* /!\ This DOES NOT ensure that the object will be available on next call !
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
*/public boolean exists( int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
T elem = _array[x][y].get();
if( elem != null )
{
return true;
}
}
return false;
}
/**
* Gets the encapsulated object
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
* @throws NoSuchElementException
*/
public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
{
T retour = null;
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
retour = _array[x][y].get();
if( retour == null )
{
throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
}
}
else
{
throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
}
return retour;
}
/**
* Add/replace an object
* @param o
* @param x
* @param y
* @throws IndexOutOfBoundsException
*/
public void set( T o , int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
}
_array[x][y] = new WeakReference<T>( o );
// store local "visible" references : avoids deletion, works in FIFO mode
_buffer.add( o );
if(_buffer.size() > _bufferSize)
{
_buffer.poll();
}
}
}
Example of how to use it :
// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
System.out.println("Image at 3,3 is still in memory");
}
You (as in the process that runs b.php
, either you through CLI
or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod()
function to set the mode of a file or folder to 777
you should use 0777
to make sure the number is correctly interpreted as an octal number.
let Device = UIDevice.currentDevice()
let iosVersion = NSString(string: Device.systemVersion).doubleValue
let iOS8 = iosVersion >= 8
let iOS7 = iosVersion >= 7 && iosVersion < 8
and check as
if(iOS8)
{
}
else
{
}
Can use this function to return line n:
def skipton(infile, n):
with open(infile,'r') as fi:
for i in range(n-1):
fi.next()
return fi.next()
Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.
An example:
function changeParam(x, y, z) {
x = 3;
y = "new string";
z["key2"] = "new";
z["key3"] = "newer";
z = {"new" : "object"};
}
var a = 1,
b = "something",
c = {"key1" : "whatever", "key2" : "original value"};
changeParam(a, b, c);
// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...
Your data structure and your JSON do not match.
Your JSON is this:
{
"JsonValues":{
"id": "MyID",
...
}
}
But the data structure you try to serialize it to is this:
class ValueSet
{
[JsonProperty("id")]
public string id
{
get;
set;
}
...
}
You are skipping a step: Your JSON is a class that has one property named JsonValues
, which has an object of your ValueSet
data structure as value.
Also inside your class your JSON is this:
"values": { ... }
Your data structure is this:
[JsonProperty("values")]
public List<Value> values
{
get;
set;
}
Note that { .. }
in JSON defines an object, where as [ .. ]
defines an array. So according to your JSON you don't have a bunch of values, but you have one
values object with the properties value1
and value2
of type Value
.
Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values
remains with it's default value: null
.
If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:
{
"id": "MyID",
"values": [
{
"id": "100",
"diaplayName": "MyValue1"
}, {
"id": "200",
"diaplayName": "MyValue2"
}
]
}
Unfortunately, WebKit browsers do not support styling of <option>
tags yet, except for color
and background-color
.
The most widely used cross browser solution is to use <ul>
/ <li>
and style them using CSS. Frameworks like Bootstrap do this well.
You can remove the back button by passing an empty new Container()
as the leading
argument to your AppBar
.
If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed
, try calling Navigator.pushReplacementNamed
to cause the earlier route to disappear.
The function pushReplacementNamed
will remove the previous route in the backstack and replace it with the new route.
Full code sample for the latter is below.
import 'package:flutter/material.dart';
class LogoutPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Logout Page"),
),
body: new Center(
child: new Text('You have been logged out'),
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Remove Back Button"),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.fullscreen_exit),
onPressed: () {
Navigator.pushReplacementNamed(context, "/logout");
},
),
);
}
}
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
routes: {
"/logout": (_) => new LogoutPage(),
},
);
}
}
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
Give this a try:
var map = {"aaa": "rrr", "bbb": "ppp"};
How about with jQuery? A simple...
$(window).load(function() { //Do the code in the {}s when the window has loaded
$("#loader").fadeOut("fast"); //Fade out the #loader div
});
And the HTML...
<div id="loader"></div>
And CSS...
#loader {
width: 100%;
height: 100%;
background-color: white;
margin: 0;
}
Then in your loader div
you would put the GIF, and any text you wanted, and it will fade out once the page has loaded.
The Eclipse team with The Open University have prepared the following document, which includes creating proxy classes with tests. It might be what you are looking for.
http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf
Everything is included in the Dynamic Web Project template.
In the project create a Web Service Client. This starts a wizard that has you point out a wsdl url and creates the client with tests for you.
The user guide (targeted at indigo though) for this task is found at http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.ws.cxf.doc.user%2Ftasks%2Fcreate_client.html.
After facing a similar issue, below is what I did :
To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");
.
Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*"
instead of any specific URL to allow any URL.
public class RestApplication
extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public MessageApplication()
{
singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
CorsFilter corsFilter = new CorsFilter();
// To allow all origins for CORS add following, otherwise add only specific urls.
// corsFilter.getAllowedOrigins().add("*");
System.out.println("To only allow restrcited urls ");
corsFilter.getAllowedOrigins().add("http://localhost:4200");
singletons = new LinkedHashSet<Object>();
singletons.add(corsFilter);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<!-- Auto scan rest service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.
Very short and sweet answer:
getActivity().onBackPressed();
Explanation of whole scenario of my case:
I have FragmentA in MainActivity, I am opening FragmentB from FragmentA (FragmentB is child or nested fragment of FragmentA)
Fragment duedateFrag = new FragmentB();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container_body, duedateFrag);
ft.addToBackStack(null);
ft.commit();
Now if you want to go to FragmentA from FragmentB you can simply put getActivity().onBackPressed();
in FragmentB.
Vertically centered Add .modal-dialog-centered to .modal-dialog to vertically center the modal
Launch demo modal
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Use the For-Each loop which came with Java 1.5, and it work on Types which are iterable.
ArrayList<String> data = new ArrayList<String>();
data.add("Vivek");
data.add("Vadodara");
data.add("Engineer");
data.add("Feelance");
for (String s : data){
System.out.prinln("Data of "+data.indexOf(s)+" "+s);
}
You can use std::find
to get an iterator to a value:
#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
myVector.erase(position);
One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.
In your Partial calling side
@Html.Partial("ParitalAction", "String data to pass to partial")
And then binding the model with Partial View like this
@model string
and the using its value in Partial View like this
@Model
You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.
Hope it helps,
revalidate
is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate
will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel
are considered dirty by the RepaintManager
.
repaint
is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.
The solution takes two steps!
First, complete the user, domain, and proxy fields in cntlm.ini
. The username and domain should probably be whatever you use to log in to Windows at your office, eg.
Username employee1730
Domain corporate
Proxy proxy.infosys.corp:8080
Then test cntlm with a command such as
cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk
It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini
, eg:
Auth NTLM
PassNT A2A7104B1CE00000000000000007E1E1
PassLM C66000000000000000000000008060C8
Finally, set the http_proxy
environment variable in Windows (assuming you didn't change with the Listen
field which by default is set to 3128
) to the following
http://localhost:3128
If you want to control the formatting of the unique identifier you can create your own <FieldType>
in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.
WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.
A solution might exist without creating a custom <FieldType>
. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]
). I haven't tried this, but this should work :)
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
There's a -f option to umount that you can try:
umount -f /mnt/fileshare
Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.
You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.
have you tried:
.image_block{
text-align: center;
vertical-align: bottom;
}
I've found the taglist plug-in a must-have. It lists all tags that it knows about (files that you have opened) in a seperate window and makes it very easy to navigate larger files.
I use it mostly for Python development, but it can only be better for C/C++.
As far as I know, the most pythonic/efficient method would be:
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
Since go
is flexible an you can create your own python
style split ...
package main
import (
"fmt"
"strings"
"errors"
)
type PyString string
func main() {
var py PyString
py = "127.0.0.1:5432"
ip, port , err := py.Split(":") // Python Style
fmt.Println(ip, port, err)
}
func (py PyString) Split(str string) ( string, string , error ) {
s := strings.Split(string(py), str)
if len(s) < 2 {
return "" , "", errors.New("Minimum match not found")
}
return s[0] , s[1] , nil
}
Why so complicated? =)
$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];
this should really do it man ;)
Use the 'break' statement. I find it humorous that the answer to your question is literally in your question! By the way, a simple Google search could have given you the answer.
As of now, Google official Text-to-Speech service is available at https://cloud.google.com/text-to-speech/
It's free for the first 4 million characters.
Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.
Starting with C#6 you can use null propagation: myList?.Any() == true
If you still find this too cloggy or prefer a good ol' extension method, I would recommend Matt Greer and Marc Gravell's answers, yet with a bit of extended functionality for completeness.
Their answers provide the same basic functionality, but each from another perspective. Matt's answer uses the string.IsNullOrEmpty
-mentality, whereas Marc's answer takes Linq's .Any()
road to get the job done.
I am personally inclined to use the .Any()
road, but would like to add the condition checking functionality from the method's other overload:
public static bool AnyNotNull<T>(this IEnumerable<T> source, Func<T, bool> predicate = null)
{
if (source == null) return false;
return predicate == null
? source.Any()
: source.Any(predicate);
}
So you can still do things like :
myList.AnyNotNull(item=>item.AnswerToLife == 42);
as you could with the regular .Any()
but with the added null check
Note that with the C#6 way: myList?.Any()
returns a bool?
rather than a bool
, which is the actual effect of propagating null
s = set([1,2,3])
print [ x for x in iter(s) ]
In terms of bytecode, in
saves a LOAD_ATTR
and replaces a CALL_FUNCTION
with a COMPARE_OP
.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in
is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in
is almost twice as fast.
You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.
use this method before show
public static ViewGroup getActivityFirstLayout(Context ctx)
{
return (ViewGroup)((ViewGroup) ActivityMaster.getActivity(ctx).findViewById(android.R.id.content)).getChildAt(0);
}
private boolean activityIsOk(Activity activity)
{
boolean s1 = !(activity == null || activity.isFinishing());
if(s1)
{
View v = LayoutMaster.getActivityFirstLayout(activity);
return v.isShown() && ViewCompat.isLaidOut(v);
}
return false;
}
A one liner that takes into account empty lists would be:
T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);
Or if you don't like null values (and performance isn't an issue):
Optional<T> lastItem = list.stream().reduce((first, second) -> second);
Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.
int remove_element(int*from, int total, int index) {
if((total - index - 1) > 0) {
memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
}
return total-1; // return the new array size
}
Note that memcpy
will not work in this case because of the overlapping memory.
One of the efficient way (better than memory move) to remove one random element is swapping with the last element.
int remove_element(int*from, int total, int index) {
if(index != (total-1))
from[index] = from[total-1];
return total; // **DO NOT DECREASE** the total here
}
But the order is changed after the removal.
Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.
int remove_element(int*from, int total, int*is_valid, int index) {
is_valid[index] = 0;
return total-1; // return the number of elements
}
It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.
int sparse_to_compact(int*arr, int total, int*is_valid) {
int i = 0;
int last = total - 1;
// trim the last invalid elements
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last
// now we keep swapping the invalid with last valid element
for(i=0; i < last; i++) {
if(is_valid[i])
continue;
arr[i] = arr[last]; // swap invalid with the last valid
last--;
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
}
return last+1; // return the compact length of the array
}
Tools -> Options -> Under the Environment section there are Fonts & Colors, change the Item Background.
If you want nice json without hardcoding attributes into your service classes,
use <webHttp defaultOutgoingResponseFormat="Json"/>
in your behavior config
function GetUserIP(){
var ret_ip;
$.ajaxSetup({async: false});
$.get('http://jsonip.com/', function(r){
ret_ip = r.ip;
});
return ret_ip;
}
If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()
Scope means the code context that performs the INSERT
statement SCOPE_IDENTITY()
, as opposed to the global scope of @@IDENTITY
.
CREATE TABLE Foo(
ID INT IDENTITY(1,1),
Dummy VARCHAR(100)
)
CREATE TABLE FooLog(
ID INT IDENTITY(2,2),
LogText VARCHAR(100)
)
go
CREATE TRIGGER InsertFoo ON Foo AFTER INSERT AS
BEGIN
INSERT INTO FooLog (LogText) VALUES ('inserted Foo')
INSERT INTO FooLog (LogText) SELECT Dummy FROM inserted
END
INSERT INTO Foo (Dummy) VALUES ('x')
SELECT SCOPE_IDENTITY(), @@IDENTITY
Gives different results.
UPDATE
or DELETE
a record isn't allowed in Hive, but INSERT INTO
is acceptable.
A snippet from Hadoop: The Definitive Guide(3rd edition):
Updates, transactions, and indexes are mainstays of traditional databases. Yet, until recently, these features have not been considered a part of Hive's feature set. This is because Hive was built to operate over HDFS data using MapReduce, where full-table scans are the norm and a table update is achieved by transforming the data into a new table. For a data warehousing application that runs over large portions of the dataset, this works well.
Hive doesn't support updates (or deletes), but it does support INSERT INTO, so it is possible to add new rows to an existing table.
The main difference between RPC and RMI is that RMI involves objects. Instead of calling procedures remotely by use of a proxy function, we instead use a proxy object.
There is greater transparency with RMI, namely due the exploitation of objects, references, inheritance, polymorphism, and exceptions as the technology is integrated into the language.
RMI is also more advanced than RPC, allowing for dynamic invocation, where interfaces can change at runtime, and object adaption, which provides an additional layer of abstraction.
SymmetricDS is the answer. It supports multiple subscribers with one direction or bi-directional asynchronous data replication. It uses web and database technologies to replicate tables between relational databases, in near real time if desired.
Comprehensive and robust Java API to suit your needs.
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
I had a navigation controllers integrated in a TabbarController. This worked
self.navigationItem.title=@"title";
When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder
add "my-resource.txt" file inside the new folder. Then in your code:
InputStream res =
Main.class.getResourceAsStream("/my-resource.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(res));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
I have a short version for you. It works well for me!
var match = str.match(/[abc]/gi);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
And if you want a prototype version:
String.prototype.indexOfRegex = function(regex){
var match = this.match(regex);
return match ? this.indexOf(match[0]) : -1;
}
String.prototype.lastIndexOfRegex = function(regex){
var match = this.match(regex);
return match ? this.lastIndexOf(match[match.length-1]) : -1;
}
EDIT : if you want to add support for fromIndex
String.prototype.indexOfRegex = function(regex, fromIndex){
var str = fromIndex ? this.substring(fromIndex) : this;
var match = str.match(regex);
return match ? str.indexOf(match[0]) + fromIndex : -1;
}
String.prototype.lastIndexOfRegex = function(regex, fromIndex){
var str = fromIndex ? this.substring(0, fromIndex) : this;
var match = str.match(regex);
return match ? str.lastIndexOf(match[match.length-1]) : -1;
}
To use it, as simple as this:
var firstIndex = str.indexOfRegex(/[abc]/gi);
var lastIndex = str.lastIndexOfRegex(/[abc]/gi);
// Example: Adding a converter to a column (C#)
Style styleReading = new Style(typeof(TextBlock));
Setter s = new Setter();
s.Property = TextBlock.ForegroundProperty;
Binding b = new Binding();
b.RelativeSource = RelativeSource.Self;
b.Path = new PropertyPath(TextBlock.TextProperty);
b.Converter = new ReadingForegroundSetter();
s.Value = b;
styleReading.Setters.Add(s);
col.ElementStyle = styleReading;
This is a gem:
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
Very brief summary:
OAuth defines four roles:
You (Resource Owner) have a mobile phone. You have several different email accounts, but you want all your email accounts in one app, so you don't need to keep switching. So your GMail (Client) asks for access (via Yahoo's Authorization Server) to your Yahoo emails (Resource Server) so you can read both emails on your GMail application.
The reason OAuth exists is because it is unsecure for GMail to store your Yahoo username and password.
You can disable them in your browser.
Type about:config
in the Firefox address bar and find security.csp.enable
and set it to false
.
You can install the extension called Disable Content-Security-Policy
to disable CSP.
'1.0-0' will give you zero decimal places i.e. no decimals. e.g.$500
Make sure you open the .xcworkspace file not the project file from xCode Project menu when working with pods. That should solve the issue with linking.
HashMap<Emp, Emp> empHashMap = new HashMap<Emp, Emp>();
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp());
empHashMap.put(new Emp(1), new Emp());
System.out.println(empHashMap.size());
}
}
class Emp{
public Emp(){
}
public Emp(int id){
this.id = id;
}
public int id;
@Override
public boolean equals(Object obj) {
return this.id == ((Emp)obj).id;
}
@Override
public int hashCode() {
return id;
}
}
OUTPUT : is 1
Means hash map wont allow duplicates, if you have properly overridden equals and hashCode() methods.
HashSet also uses HashMap internally, see the source doc
public class HashSet{
public HashSet() {
map = new HashMap<>();
}
}
Use a timer with an interval set to 2–3 seconds.
You have three different options to choose from, depending on which type of application you're writing:
Don't use Thread.Sleep
if your application need to process any inputs on that thread at the same time (WinForms, WPF), as Sleep
will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just delaying an operation as you probably intended. Note that it may be fine to use Sleep in pure console application as there are no "events" to handle or on separate thread (also Task.Delay
is better option).
In addition to timers and Sleep
you can use Task.Delay
which is asynchronous version of Sleep
that does not block thread from processing events (if used properly - don't turn it into infinite sleep with .Wait()
).
public async void ClickHandler(...)
{
// whatever you need to do before delay goes here
await Task.Delay(2000);
// whatever you need to do after delay.
}
The same await Task.Delay(2000)
can be used in a Main
method of a console application if you use C# 7.1 (Async main on MSDN blogs).
Note: delaying operation with Sleep
has benefit of avoiding race conditions that comes from potentially starting multiple operations with timers/Delay
. Unfortunately freezing UI-based application is not acceptable so you need to think about what will happen if you start multiple delays (i.e. if it is triggered by a button click) - consider disabling such button, or canceling the timer/task or making sure delayed operation can be done multiple times safely.
best easy solution:
[PATH MYSQL]/bin/mysql -u root
[Enter password]
SET GLOBAL default_password_lifetime = 0;
and then works fine.
In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.
appparently it's a XLS file and not a CSV file as http://www.garykessler.net/library/file_sigs.html confirm
Create a folder named fonts in the assets folder and add the snippet from the below link.
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);
Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.
See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).
try plot(var); saveFigure('title'); it will save as a jpeg automatically
The below method to migrate my GIT Stash to GitLab by maintaining all branches and preserving history.
Clone the old repository to local.
git clone --bare <STASH-URL>
Create an empty repository in GitLab.
git push --mirror <GitLab-URL>
The above I performed when we migrated our code from stash to GitLab and it worked very well.
Because you are assigning instance
to null
. The compiler infers that it can never be anything other than null
. So it assumes that the else block should never be executed so instance
is typed as never
in the else block.
Now if you don't declare it as the literal value null
, and get it by any other means (ex: let instance: Foo | null = getFoo();
), you will see that instance
will be null
inside the if block and Foo
inside the else block.
Never type documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html#never
Edit:
The issue in the updated example is actually an open issue with the compiler. See:
https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176
Please give a try with below code.
var Item = GetAll().GroupBy(x => x .Id).ToList();
public enum MyEnum
{
ONE(1),
TWO(2);
private int value;
private MyEnum(int val){
value = val;
}
public int getValue(){
return value;
}
}
Without using CDATA, try
<xsl:value-of select="'
'" />
Note the double and single quotes.
That is particularly useful if you are not creating xml
aka text. <xsl:output method="text" />
Remove/Delete the project from workspace. and Reimport the project to the workspace. This method worked for me.
If you have experience write simple scripts by Perl\Python\etc, and convert MySQL to SQLite. Read data from Mysql and write it on SQLite.
(string)((int)"00000234892839")
You can enable SSL on XAMPP by creating self signed certificates and then installing those certificates. Type the below commands to generate and move the certificates to ssl folders.
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
cp server.crt /opt/lampp/etc/ssl.crt/domainname.crt
cp server.key /opt/lampp/etc/ssl.key/domainname.key
(Use sudo with each command if you are not the super user)
Now, Check that mod_ssl is enabled in [XAMPP_HOME]/etc/httpd.conf:
LoadModule ssl_module modules/mod_ssl.so
Add a virtual host, in this example "localhost.domainname.com" by editing [XAMPP_HOME]/etc/extra/httpd-ssl.conf as follows:
<virtualhost 127.0.1.4:443>
ServerName localhost.domainname.com
ServerAlias localhost.domainname.com *.localhost.domainname.com
ServerAdmin admin@localhost
DocumentRoot "/opt/lampp/htdocs/"
DirectoryIndex index.php
ErrorLog /opt/lampp/logs/domainname.local.error.log
CustomLog /opt/lampp/logs/domainname.local.access.log combined
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile /opt/lampp/etc/ssl.crt/domainname.crt
SSLCertificateKeyFile /opt/lampp/etc/ssl.key/domainname.key
<directory /opt/lampp/htdocs/>
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</directory>
BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
</virtualhost>
Add the following entry to /etc/hosts:
127.0.1.4 localhost.domainname.com
Now, try installing the certificate/ try importing certificate to browser. I have checked this and this worked on Ubuntu.
You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.
This way you can determine when your functionality gets executed and also when the program exists.
startProgram()
{
Console.WriteLine("-------Program starts--------");
Console.Read();
}
endProgram()
{
Console.WriteLine("-------Program Ends--------");
Console.Read();
}
This should actually do what the OP specifies:
One-liner in Bash:
$ for first_level in `find . -maxdepth 1 -type d`; do find $first_level -printf "%TY-%Tm-%Td %TH:%TM:%TS $first_level\n" | sort -n | tail -n1 ; done
which gives output such as:
2020-09-12 10:50:43.9881728000 .
2020-08-23 14:47:55.3828912000 ./.cache
2018-10-18 10:48:57.5483235000 ./.config
2019-09-20 16:46:38.0803415000 ./.emacs.d
2020-08-23 14:48:19.6171696000 ./.local
2020-08-23 14:24:17.9773605000 ./.nano
This lists each first-level directory with the human-readable timestamp of the latest file within those folders, even if it is in a subfolder, as requested in
"I need to make a list of all these directories that is constructed in a way such that every first-level directory is listed next to the date and time of the latest created/modified file within it."
Here's another approach:
Point C (x3,y3) will lie between A & B if:
^[0-9][0-9]?[^A-Za-z0-9]?po$
You can test it here: http://www.regextester.com/
To use this in C#,
Regex r = new Regex(@"^[0-9][0-9]?[^A-Za-z0-9]?po$");
if (r.Match(someText).Success) {
//Do Something
}
Remember, @ is a useful symbol that means the parser takes the string literally (eg, you don't need to write \\ for one backslash)
Swift 3 (forget about NSURL).
let fileName = "20-01-2017 22:47"
let folderString = "file:///var/mobile/someLongPath"
To make a URL out of a string:
let folder: URL? = Foundation.URL(string: folderString)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath
If we want to add the filename. Note, that appendingPathComponent() adds the percent encoding automatically:
let folderWithFilename: URL? = folder?.appendingPathComponent(fileName)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath/20-01-2017%2022:47
When we want to have String but without the root part (pay attention that percent encoding is removed automatically):
let folderWithFilename: String? = folderWithFilename.path
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017 22:47"
If we want to keep the root part we do this (but mind the percent encoding - it is not removed):
let folderWithFilenameAbsoluteString: String? = folderWithFilenameURL.absoluteString
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017%2022:47"
To manually add the percent encoding for a string:
let folderWithFilenameAndEncoding: String? = folderWithFilename.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017%2022:47"
To remove the percent encoding:
let folderWithFilenameAbsoluteStringNoEncodig: String? = folderWithFilenameAbsoluteString.removingPercentEncoding
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017 22:47"
The percent-encoding is important because URLs for network requests need them, while URLs to file system won't always work - it depends on the actual method that uses them. The caveat here is that they may be removed or added automatically, so better debug these conversions carefully.
CREATE VIEW MyView AS
SELECT Column, Value FROM Table;
SELECT Column FROM MyView WHERE Value = 1;
Is the proper solution in MySQL, some other SQLs let you define Views more exactly.
Note: Unless the View is very complicated, MySQL will optimize this just fine.
You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.
Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.
The below code helps me to return a JSON object for JavaScript on the front end
My template code
template_file.json
{
"name": "{{name}}"
}
Python backed code
def download_json(request):
print("Downloading JSON")
# Response render a template as JSON object
return HttpResponse(render_to_response("template_file.json",dict(name="Alex Vera")),content_type="application/json")
File url.py
url(r'^download_as_json/$', views.download_json, name='download_json-url')
jQuery code for the front end
$.ajax({
url:'{% url 'download_json-url' %}'
}).done(function(data){
console.log('json ', data);
console.log('Name', data.name);
alert('hello ' + data.name);
});
I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.
I generally use this to reset the git to the specific commit in source tree.
select commit to reset on sourcetree.
In dropdowns select the active branch , first Parent Only
And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)
and then go to terminal git push -f
You should be all set!
With the use of jQuery to handle the document ready event,
<script type="text/javascript">
function onLoadAlert() {
alert('<%: TempData["Resultat"]%>');
}
$(document).ready(onLoadAlert);
</script>
Or, even simpler - put the <script>
at the end of body
, not in the head
.
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
It is absolutely possible to install side-by-side several JRE/JDK versions. Moreover, you don't have to do anything special for that to happen, as Sun is creating a different folder for each (under Program Files).
There is no control panel to check which JRE works for each application. Basically, the JRE that will work would be the first in your PATH environment variable. You can change that, or the JAVA_HOME variable, or create specific cmd/bat files to launch the applications you desire, each with a different JRE in path.
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".
http://www.w3schools.com/html5/tag_iframe.asp
or you can use
<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>
Firebase Notifications doesn't have an API to send messages. Luckily it is built on top of Firebase Cloud Messaging, which has precisely such an API.
With Firebase Notifications and Cloud Messaging, you can send so-called downstream messages to devices in three ways:
You'll note that there is no way to send to all devices explicitly. You can build such functionality with each of these though, for example: by subscribing the app to a topic when it starts (e.g. /topics/all
) or by keeping a list of all device IDs, and then sending the message to all of those.
For sending to a topic you have a syntax error in your command. Topics are identified by starting with /topics/
. Since you don't have that in your code, the server interprets allDevices
as a device id. Since it is an invalid format for a device registration token, it raises an error.
From the documentation on sending messages to topics:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser
ngrok http 8080 -host-header="localhost:8080"
ngrok http --host-header=rewrite 8080
obviously replace 8080 with whatever port you're running on
this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost, when this is embedded, it's looking to localhost, which the app is no longer running on
Wrap your $adr
in urlencode()
.
I was having this problem and this solved it for me.
You can use Edit > Column Editor...
to insert text at the current and following lines. The shortcut is Alt + C.
$array1 = "Orange";
$array2 = array("Apple","Grapes","Orange","Pineapple");
if(in_array($array1,$array2)){
echo $array1.' exists in array2';
}else{
echo $array1.'does not exists in array2';
}
You can find the answer in this video https://www.youtube.com/watch?v=SYoN-OvdZ3M&list=PLonJJ3BVjZW6CtAMbJz1XD8ELUs1KXaTD&index=19 and the next 3 videos. All the touch events are explained very well, it's very clear and full of examples.
I think the shortest way is:
var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();
As described here, you can redefine the command \qedsymbol
, in your case - to \blacksquare
:
\renewcommand{\qedsymbol}{\ensuremath{\blacksquare}}
This works both with \qed
command and proof
environment.
Instead of running perror
on any error code you get, you can retrieve a complete listing of errno
values on your system with the following one-liner:
cpp -dM /usr/include/errno.h | grep 'define E' | sort -n -k 3
Here I have tried this CSS for all major browser & tested: Custom color are working fine on scrollbar.
Yes, there are limitations on several versions of different browsers.
/* Only Chrome */
html::-webkit-scrollbar {width: 17px;}
html::-webkit-scrollbar-thumb {background-color: #0064a7; background-clip: padding-box; border: 1px solid #8ea5b5;}
html::-webkit-scrollbar-track {background-color: #8ea5b5; }
::-webkit-scrollbar-button {background-color: #8ea5b5;}
/* Only IE */
html {scrollbar-face-color: #0064a7; scrollbar-shadow-color: #8ea5b5; scrollbar-highlight-color: #8ea5b5;}
/* Only FireFox */
html {scrollbar-color: #0064a7 #8ea5b5;}
/* View Scrollbar */
html {overflow-y: scroll;overflow-x: hidden;}
_x000D_
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<header>
<div id="logo"><img src="/logo.png">HTML5 Layout</div>
<nav>
<ul>
<li><a href="/">Home</a>
<li><a href="https://html-css-js.com/">HTML</a>
<li><a href="https://html-css-js.com/css/code/">CSS</a>
<li><a href="https://htmlcheatsheet.com/js/">JS</a>
</ul>
</nav>
</header>
<section>
<strong>Demonstration of a simple page layout using HTML5 tags: header, nav, section, main, article, aside, footer, address.</strong>
</section>
<section id="pageContent">
<main role="main">
<article>
<h2>Stet facilis ius te</h2>
<p>Lorem ipsum dolor sit amet, nonumes voluptatum mel ea, cu case ceteros cum. Novum commodo malorum vix ut. Dolores consequuntur in ius, sale electram dissentiunt quo te. Cu duo omnes invidunt, eos eu mucius fabellas. Stet facilis ius te, quando voluptatibus eos in. Ad vix mundi alterum, integre urbanitas intellegam vix in.</p>
</article>
<article>
<h2>Illud mollis moderatius</h2>
<p>Eum facete intellegat ei, ut mazim melius usu. Has elit simul primis ne, regione minimum id cum. Sea deleniti dissentiet ea. Illud mollis moderatius ut per, at qui ubique populo. Eum ad cibo legimus, vim ei quidam fastidii.</p>
</article>
<article>
<h2>Ex ignota epicurei quo</h2>
<p>Quo debet vivendo ex. Qui ut admodum senserit partiendo. Id adipiscing disputando eam, sea id magna pertinax concludaturque. Ex ignota epicurei quo, his ex doctus delenit fabellas, erat timeam cotidieque sit in. Vel eu soleat voluptatibus, cum cu exerci mediocritatem. Malis legere at per, has brute putant animal et, in consul utamur usu.</p>
</article>
<article>
<h2>His at autem inani volutpat</h2>
<p>Te has amet modo perfecto, te eum mucius conclusionemque, mel te erat deterruisset. Duo ceteros phaedrum id, ornatus postulant in sea. His at autem inani volutpat. Tollit possit in pri, platonem persecuti ad vix, vel nisl albucius gloriatur no.</p>
</article>
</main>
<aside>
<div>Sidebar 1</div>
<div>Sidebar 2</div>
<div>Sidebar 3</div>
</aside>
</section>
<footer>
<p>© You can copy, edit and publish this template but please leave a link to our website | <a href="https://html5-templates.com/" target="_blank" rel="nofollow">HTML5 Templates</a></p>
<address>
Contact: <a href="mailto:[email protected]">Mail me</a>
</address>
</footer>
</body>
</html>
_x000D_
Yes, querySelectorAll
does take a group of selectors:
form, p, legend
today this kind of thing can be done by using display:flex;
https://jsfiddle.net/suunyz3e/1435/
html:
<div class="container flex-direction">
<div class="div1">
<span>Div One</span>
</div>
<div class="div2">
<span>Div Two</span>
</div>
</div>
css:
.container{
display:inline-flex;
flex-wrap:wrap;
border:1px solid black;
}
.flex-direction{
flex-direction:row;
}
.div1{
border-right:1px solid black;
background-color:#727272;
width:165px;
height:132px;
}
.div2{
background-color:#fff;
width:314px;
height:132px;
}
span{
font-size:16px;
font-weight:bold;
display: block;
line-height: 132px;
text-align: center;
}
@media screen and (max-width: 500px) {
.flex-direction{
flex-direction:column;
}
.div1{
width:202px;
height:131px;
border-right:none;
border-bottom:1px solid black;
}
.div2{
width:202px;
height:107px;
}
.div2 span{
line-height:107px;
}
}
TO PREVIEW MULTIPLE FILES using jquery
$(document).ready(function(){
$('#image').change(function(){
$("#frames").html('');
for (var i = 0; i < $(this)[0].files.length; i++) {
$("#frames").append('<img src="'+window.URL.createObjectURL(this.files[i])+'" width="100px" height="100px"/>');
}
});
});
_x000D_
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="image" name="image[]" multiple /><br/>
<div id="frames"></div>
</body>
_x000D_
If you know the element type then: (eg: replace 'element' with 'div')
$("element[id$='txtTitle']")
If you don't know the element type:
$("[id$='txtTitle']")
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
$("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
As Alexander Logger pointed out in zendars answer, you have to send something to be completely sure. In case your connected partner does not read on this socket at all, you can use the following code.
bool SocketConnected(Socket s)
{
// Exit if socket is null
if (s == null)
return false;
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
{
try
{
int sentBytesCount = s.Send(new byte[1], 1, 0);
return sentBytesCount == 1;
}
catch
{
return false;
}
}
}
But even then it might take a few seconds until a broken network cable or something similar is detected.
Other that the differences in the default access (public/private), there is no difference.
However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."
Note that C unions work with C++, but not the other way around. For example
union WorksWithCppOnly{
WorksWithCppOnly():a(0){}
friend class FloatAccessor;
int a;
private:
float b;
};
And likewise
typedef union friend{
int a;
float b;
} class;
only works in C
#!/bin/bash
if getopts "n:" arg; then
echo "Welcome $OPTARG"
fi
Save it as sample.sh and try running
sh sample.sh -n John
in your terminal.
All the other answers will work on Angular version < 6.1. But if you've got the latest version then you won't need to do these ugly hacks as Angular has fixed the issue.
All you'd need to do is set scrollOffset
with the option of the second argument ofRouterModule.forRoot
method.
@NgModule({
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
scrollOffset: [0, 64] // [x, y]
})
],
exports: [RouterModule]
})
export class AppRoutingModule {}
Diff between Finalize and Dispose methods in C#.
GC calls the finalize method to reclaim the unmanaged resources(such as file operarion, windows api, network connection, database connection) but time is not fixed when GC would call it. It is called implicitly by GC it means we do not have low level control on it.
Dispose Method: We have low level control on it as we call it from the code. we can reclaim the unmanaged resources whenever we feel it is not usable.We can achieve this by implementing IDisposal pattern.
I believe Node.js is best suited for real-time applications: online games, collaboration tools, chat rooms, or anything where what one user (or robot? or sensor?) does with the application needs to be seen by other users immediately, without a page refresh.
I should also mention that Socket.IO in combination with Node.js will reduce your real-time latency even further than what is possible with long polling. Socket.IO will fall back to long polling as a worst case scenario, and instead use web sockets or even Flash if they are available.
But I should also mention that just about any situation where the code might block due to threads can be better addressed with Node.js. Or any situation where you need the application to be event-driven.
Also, Ryan Dahl said in a talk that I once attended that the Node.js benchmarks closely rival Nginx for regular old HTTP requests. So if we build with Node.js, we can serve our normal resources quite effectively, and when we need the event-driven stuff, it's ready to handle it.
Plus it's all JavaScript all the time. Lingua Franca on the whole stack.
If you extend String object like this..
String.prototype.float = function() {
return parseFloat(this.replace(',', '.'));
}
.. you can run it like this
"554,20".float()
> 554.20
works with dot as well
"554.20".float()
> 554.20
typeof "554,20".float()
> "number"
(My original answer was wrong, sorry for the bad math, see below the break.)
How about this?
The first 27 bits store the lowest number you have seen, then the difference to the next number seen, encoded as follows: 5 bits to store the number of bits used in storing the difference, then the difference. Use 00000 to indicate that you saw that number again.
This works because as more numbers are inserted, the average difference between numbers goes down, so you use less bits to store the difference as you add more numbers. I believe this is called a delta list.
The worst case I can think of is all numbers evenly spaced (by 100), e.g. Assuming 0 is the first number:
000000000000000000000000000 00111 1100100
^^^^^^^^^^^^^
a million times
27 + 1,000,000 * (5+7) bits = ~ 427k
Reddit to the rescue!
If all you had to do was sort them, this problem would be easy. It takes 122k (1 million bits) to store which numbers you have seen (0th bit on if 0 was seen, 2300th bit on if 2300 was seen, etc.
You read the numbers, store them in the bit field, and then shift the bits out while keeping a count.
BUT, you have to remember how many you have seen. I was inspired by the sublist answer above to come up with this scheme:
Instead of using one bit, use either 2 or 27 bits:
I think this works: if there are no duplicates, you have a 244k list. In the worst case you see each number twice (if you see one number three times, it shortens the rest of the list for you), that means you have seen 50,000 more than once, and you have seen 950,000 items 0 or 1 times.
50,000 * 27 + 950,000 * 2 = 396.7k.
You can make further improvements if you use the following encoding:
0 means you did not see the number 10 means you saw it once 11 is how you keep count
Which will, on average, result in 280.7k of storage.
EDIT: my Sunday morning math was wrong.
The worst case is we see 500,000 numbers twice, so the math becomes:
500,000 *27 + 500,000 *2 = 1.77M
The alternate encoding results in an average storage of
500,000 * 27 + 500,000 = 1.70M
: (
The python issue with using npm
on an out-of-the-box Cygwin installation, is that node-gyp
is giving a misleading error due to incomplete checking in the ../npm/node_modules/node-gyp/lib/configure.js
code.
It's due to how Cygwin treats symbolic links. It doesn't do that properly in an out-of-the box installation. So the error messages from the above code become misleading, as it complains about the PYTHON
path and not the existence of python.exe
(or link of) file itself.
There are (at least) 2 ways to resolve this.
cygutils-extra
and use winln
.For (1) you can create a proper symlink from within Cygwin shell by doing these steps:
# To make the Cygwin environment treat Windows links properly:
# Alternatively add this to your `.bashrc` for permanent use.
export CYGWIN=winsymlinks:nativestrict
# Install Cygwin package containing "winln"
apt-cyg install cygutils-extra
# Make a proper Windows sym-link:
cd /cygdrive/c/cygwin64/bin/
winln.exe -s python2.7.exe python.exe
# Add PYTHON as a native Windows system wide variable (HKLM)
setx /M PYTHON "C:\cygwin64\bin\python"
(Also assuming you are running the Cygwin shell as Admin.)
Using apt-cyg
is recommended and can be found in various forms on github.
For (2) the resolution for out-of-the-box Cygwin users is this:
# Open a native Windows CMD in Administrator mode and:
cd C:\cygwin64\bin\
mklink python.exe python2.7.exe
The result should look like this:
C:\cygwin64\bin>ls -al python*
lrwxrwxrwx 1 xxx xxx 13 Jun 2 2015 python -> python2.7.exe
lrwxrwxrwx 1 Administrators xxx 13 Aug 24 17:28 python.exe -> python2.7.exe
lrwxrwxrwx 1 xxx xxx 13 Jun 2 2015 python2 -> python2.7.exe
-rwxr-xr-x 1 xxx xxx 9235 Jun 2 2015 python2.7.exe
How about:
df . -B MB | tail -1 | awk {'print $4'} | cut -d'%' -f1
Use SemaphoreSlim.WaitAsync
method.
await mySemaphoreSlim.WaitAsync();
try {
await Stuff();
} finally {
mySemaphoreSlim.Release();
}
.svn
's parent directoryjust this steps helped me to resolve:
svn: E155004: Working copy 'resourceAddress' locked
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')
In your instance it would be
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')
Because there is no replacement (you want to get rid of it).
This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.
And if you have lot insert queries but not wanna ger a ERROR message everytime , you can do it:
CREATE UNIQUE NONCLUSTERED INDEX SK01 ON dbo.Person(ID,Name,Active,PersonNumber)
WITH(IGNORE_DUP_KEY = ON)
Use the break statement: http://docs.python.org/reference/simple_stmts.html#break
Calling stopPropagation
on the event prevents propagation:
(event)="doSomething($event); $event.stopPropagation()"
For preventDefault
just return false
(event)="doSomething($event); false"
Event binding allows to execute multiple statements and expressions to be executed sequentially (separated by ;
like in *.ts
files.
The result of last expression will cause preventDefault
to be called if falsy. So be cautious what the expression returns (even when there is only one)
An easy approach would be making all the blank cells NA
and only keeping complete cases. You might also look for na.omit
examples. It is a widely discussed topic.
df[df==""]<-NA
df<-df[complete.cases(df),]
The linker takes some environment variables into account. one is LD_PRELOAD
from man 8 ld-linux
:
LD_PRELOAD
A whitespace-separated list of additional, user-specified, ELF
shared libraries to be loaded before all others. This can be
used to selectively override functions in other shared
libraries. For setuid/setgid ELF binaries, only libraries in
the standard search directories that are also setgid will be
loaded.
Therefore the linker will try to load libraries listed in the LD_PRELOAD
variable before others are loaded.
What could be the case that inside the variable is listed a library that can't be pre-loaded. look inside your .bashrc
or .bash_profile
environment where the LD_PRELOAD
is set and remove that library from the variable.
setTimeout will help you to execute any JavaScript code based on the time you set.
Syntax
setTimeout(code, millisec, lang)
Usage,
setTimeout("function1()", 1000);
For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp
When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().
Sample code (in an Activity):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}
This will search all the related files in current and sub directories, calculating their line count separately as well as totally:
find . -name "*.wanted" | xargs wc -l
I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:
python manage.py startapp new_app
settings.py
file, adding the following to the list of INSTALLED_APPS
: 'new_app',
new_app
package named new_app_tags
.{% extends 'base_template_name.html' %}
: {% load new_app_tags %}
new_app_tags
module file, create a custom template tag (see below).{% multiply_by_two | "5.0" %}
Example from step 5 above:
from django import template
register = template.Library()
@register.simple_tag
def multiply_by_two(value):
return float(value) * 2.0
Use application/javascript
as content type instead of text/javascript
text/javascript
is mentioned obsolete. See reference docs.
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
UPDATE:
I have tried executing the code you have given and the below didn't work.
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()
there.
one of the easy way is using shortcuts like : Ctrl+F10, then press n "it show line number and hide line numbers.
There's not really any "raw string"; there are raw string literals, which are exactly the string literals marked by an 'r'
before the opening quote.
A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, \
, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence.
This syntax variant exists mostly because the syntax of regular expression patterns is heavy with backslashes (but never at the end, so the "except" clause above doesn't matter) and it looks a bit better when you avoid doubling up each of them -- that's all. It also gained some popularity to express native Windows file paths (with backslashes instead of regular slashes like on other platforms), but that's very rarely needed (since normal slashes mostly work fine on Windows too) and imperfect (due to the "except" clause above).
r'...'
is a byte string (in Python 2.*), ur'...'
is a Unicode string (again, in Python 2.*), and any of the other three kinds of quoting also produces exactly the same types of strings (so for example r'...'
, r'''...'''
, r"..."
, r"""..."""
are all byte strings, and so on).
Not sure what you mean by "going back" - there is no intrinsically back and forward directions, because there's no raw string type, it's just an alternative syntax to express perfectly normal string objects, byte or unicode as they may be.
And yes, in Python 2.*, u'...'
is of course always distinct from just '...'
-- the former is a unicode string, the latter is a byte string. What encoding the literal might be expressed in is a completely orthogonal issue.
E.g., consider (Python 2.6):
>>> sys.getsizeof('ciao')
28
>>> sys.getsizeof(u'ciao')
34
The Unicode object of course takes more memory space (very small difference for a very short string, obviously ;-).
Use this below code to display pop-up box on page load:
$(document).ready(function() {
var id = '#dialog';
var maskHeight = $(document).height();
var maskWidth = $(window).width();
$('#mask').css({'width':maskWidth,'height':maskHeight});
$('#mask').fadeIn(500);
$('#mask').fadeTo("slow",0.9);
var winH = $(window).height();
var winW = $(window).width();
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
$(id).fadeIn(2000);
$('.window .close').click(function (e) {
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
<div class="maintext">
<h2> Main text goes here...</h2>
</div>
<div id="boxes">
<div style="top: 50%; left: 50%; display: none;" id="dialog" class="window">
<div id="san">
<a href="#" class="close agree"><img src="close-icon.png" width="25" style="float:right; margin-right: -25px; margin-top: -20px;"></a>
<img src="san-web-corner.png" width="450">
</div>
</div>
<div style="width: 2478px; font-size: 32pt; color:white; height: 1202px; display: none; opacity: 0.4;" id="mask"></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
I refereed this code from here Demo
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
Easiest solution I figured was,
add '/' to the route that want to be reloaded every time when coming back.
eg:
instead of the following
$routeProvider
.when('/About', {
templateUrl: 'about.html',
controller: 'AboutCtrl'
})
use,
$routeProvider
.when('/About/', { //notice the '/' at the end
templateUrl: 'about.html',
controller: 'AboutCtrl'
})
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
In MySQL:
create table temp as select * from original_table
One of the differences is in short
UDP : Send message and dont look back if it reached destination, Connectionless protocol
TCP : Send message and guarantee to reach destination, Connection-oriented protocol
The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar
is quite useful for such things.
The best answer for your question is to use the new xparse
package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.
In your example you have a \sec
macro that either takes one or two braced arguments. This would be implemented using xparse
with the following:
\documentclass{article} \usepackage{xparse} \begin{document} \DeclareDocumentCommand\sec{ m g }{% {#1% \IfNoValueF {#2} { and #2}% }% } (\sec{Hello}) (\sec{Hello}{Hi}) \end{document}
The argument { m g }
defines the arguments of \sec
; m
means "mandatory argument" and g
is "optional braced argument". \IfNoValue(T)(F)
can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.
Use html_entity_decode()
and htmlentities()
.
$html = html_entity_decode(htmlentities($html, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-1');
htmlentities()
formats your input into UTF8
and html_entity_decode()
formats it back to ISO-8859-1
.
Run below SQL query to create a view which will show all functions:
CREATE OR REPLACE VIEW show_functions AS
SELECT routine_name FROM information_schema.routines
WHERE routine_type='FUNCTION' AND specific_schema='public';
Java EE 5 favors the use of annotations over XML configuration. For example, in EJB3 the transaction attributes on an EJB method are specified using annotations. They even use annotations to mark POJOs as EJBs and to specify particular methods as lifecycle methods instead of requiring that implementation of an interface.
The element outerHTML
property (note: supported by Firefox after version 11) returns the HTML of the entire element.
<div id="new-element-1">Hello world.</div>
<script type="text/javascript"><!--
var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>
--></script>
Similarly, you can use innerHTML
to get the HTML contained within a given element, or innerText
to get the text inside an element (sans HTML markup).
Your function is probably in a different namespace than the one you're calling it from.
Using Java 8's Stream.filter()
method in combination with List.contains()
:
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
/* ... */
List<Integer> list1 = asList(1, 2, 3, 4, 5);
List<Integer> list2 = asList(1, 3, 5, 7, 9);
List<Integer> common = list1.stream().filter(list2::contains).collect(toList());
This problem arrive when you are proxy issue or slow network. You can go with the depth solution or
git fetch --all or git clone
If this give error of curl 56 Recv failure then download the file via zip or spicify the name of branch instead of --all
git fetch origin BranchName
Using using
is a pretty good way:
using (MyForm foo = new MyForm())
{
if (foo.ShowDialog() == DialogResult.OK)
{
// your code
}
}
network solutions offers the advice to put a php.ini in the cgi-bin to enable mod_rewrite
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
All string functions as lower
, upper
, strip
are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable
, it will fail.
x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them
http://bootsnipp.com/snippets/featured/circle-button?
CSS:
.btn-circle { width: 30px; height: 30px; text-align: center;padding: 6px 0;font-size: 12px;line-height: 1.428571429;border-radius: 15px;}.btn-circle.btn-lg {width: 50px;height: 50px;padding: 10px 16px;font-size: 18px;line-height:1.33;border-radius: 25px;}
In my experience, the most friendly way of dealing with this is to have a function that converts a string into a table of values.
There are many splitter functions available on the web, you'll easily find one for whatever if your flavour of SQL.
You can then do...
SELECT * FROM table WHERE id IN (SELECT id FROM split(@list_of_ids))
Or
SELECT * FROM table INNER JOIN (SELECT id FROM split(@list_of_ids)) AS list ON list.id = table.id
(Or similar)
header('Content-type: text/plain; charset=utf-8');
On mac, open the terminal and type:
cd /usr/local/mysql/bin
then type:
./mysql -u root -p
It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.
Libman seems to be the tool preferred by Microsoft now. It is integrated in Visual Studio 2017(15.8).
This article describes how to use it and even how to set up a restore performed by the build process.
Bootstrap's documentation tells you what files you need in your project.
The following example should work as a configuration for libman.json.
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "[email protected]",
"destination": "wwwroot/lib/bootstrap",
"files": [
"js/bootstrap.bundle.js",
"css/bootstrap.min.css"
]
},
{
"library": "[email protected]",
"destination": "wwwroot/lib/jquery",
"files": [
"jquery.min.js"
]
}
]
}
You go File->Settings->Gradle Look at the "Offline work" inbox, if it's checked u uncheck and try to sync again I have the same problem and i try this , the problem resolved. Good luck !
Warn/confirm User if Back button is Pressed is as below.
window.onbeforeunload = function() { return "Your work will be lost."; };
You can get more information using below mentioned links.
Disable Back Button in Browser using JavaScript
I hope this will help to you.
To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab.
Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.
Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.
See attachments. I hope this could be useful for anyone.
Very simple you have to just put
\n
where ever you want to break line in your string resource.
For example
String s = my string resource have \n line break here;
Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.
variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0
name = name + str(i) #this will be your variable name.
while True:
value = 10 #value to assign
variables.update(
{name:value})
if break_condition == True:
break
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>
run cmd.exe
and do the following:
> cd "long path name"
> command
Then command.com will come up and display only short paths.
How to iterate over rows in a DataFrame in Pandas?
Iteration in Pandas is an anti-pattern and is something you should only do when you have exhausted every other option. You should not use any function with "iter
" in its name for more than a few thousand rows or you will have to get used to a lot of waiting.
Do you want to print a DataFrame? Use DataFrame.to_string()
.
Do you want to compute something? In that case, search for methods in this order (list modified from here):
for
loop)DataFrame.apply()
: i) Reductions that can be performed in Cython, ii) Iteration in Python spaceDataFrame.itertuples()
and iteritems()
DataFrame.iterrows()
iterrows
and itertuples
(both receiving many votes in answers to this question) should be used in very rare circumstances, such as generating row objects/nametuples for sequential processing, which is really the only thing these functions are useful for.
Appeal to Authority
The documentation page on iteration has a huge red warning box that says:
Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed [...].
* It's actually a little more complicated than "don't". df.iterrows()
is the correct answer to this question, but "vectorize your ops" is the better one. I will concede that there are circumstances where iteration cannot be avoided (for example, some operations where the result depends on the value computed for the previous row). However, it takes some familiarity with the library to know when. If you're not sure whether you need an iterative solution, you probably don't. PS: To know more about my rationale for writing this answer, skip to the very bottom.
A good number of basic operations and computations are "vectorised" by pandas (either through NumPy, or through Cythonized functions). This includes arithmetic, comparisons, (most) reductions, reshaping (such as pivoting), joins, and groupby operations. Look through the documentation on Essential Basic Functionality to find a suitable vectorised method for your problem.
If none exists, feel free to write your own using custom Cython extensions.
List comprehensions should be your next port of call if 1) there is no vectorized solution available, 2) performance is important, but not important enough to go through the hassle of cythonizing your code, and 3) you're trying to perform elementwise transformation on your code. There is a good amount of evidence to suggest that list comprehensions are sufficiently fast (and even sometimes faster) for many common Pandas tasks.
The formula is simple,
# Iterating over one column - `f` is some function that processes your data
result = [f(x) for x in df['col']]
# Iterating over two columns, use `zip`
result = [f(x, y) for x, y in zip(df['col1'], df['col2'])]
# Iterating over multiple columns - same data type
result = [f(row[0], ..., row[n]) for row in df[['col1', ...,'coln']].to_numpy()]
# Iterating over multiple columns - differing data type
result = [f(row[0], ..., row[n]) for row in zip(df['col1'], ..., df['coln'])]
If you can encapsulate your business logic into a function, you can use a list comprehension that calls it. You can make arbitrarily complex things work through the simplicity and speed of raw Python code.
Caveats
List comprehensions assume that your data is easy to work with - what that means is your data types are consistent and you don't have NaNs, but this cannot always be guaranteed.
zip(df['A'], df['B'], ...)
instead of df[['A', 'B']].to_numpy()
as the latter implicitly upcasts data to the most common type. As an example if A is numeric and B is string, to_numpy()
will cast the entire array to string, which may not be what you want. Fortunately zip
ping your columns together is the most straightforward workaround to this.*Your mileage may vary for the reasons outlined in the Caveats section above.
Let's demonstrate the difference with a simple example of adding two pandas columns A + B
. This is a vectorizable operaton, so it will be easy to contrast the performance of the methods discussed above.
Benchmarking code, for your reference. The line at the bottom measures a function written in numpandas, a style of Pandas that mixes heavily with NumPy to squeeze out maximum performance. Writing numpandas code should be avoided unless you know what you're doing. Stick to the API where you can (i.e., prefer vec
over vec_numpy
).
I should mention, however, that it isn't always this cut and dry. Sometimes the answer to "what is the best method for an operation" is "it depends on your data". My advice is to test out different approaches on your data before settling on one.
10 Minutes to pandas, and Essential Basic Functionality - Useful links that introduce you to Pandas and its library of vectorized*/cythonized functions.
Enhancing Performance - A primer from the documentation on enhancing standard Pandas operations
Are for-loops in pandas really bad? When should I care? - a detailed writeup by me on list comprehensions and their suitability for various operations (mainly ones involving non-numeric data)
When should I (not) want to use pandas apply() in my code? - apply
is slow (but not as slow as the iter*
family. There are, however, situations where one can (or should) consider apply
as a serious alternative, especially in some GroupBy
operations).
* Pandas string methods are "vectorized" in the sense that they are specified on the series but operate on each element. The underlying mechanisms are still iterative, because string operations are inherently hard to vectorize.
A common trend I notice from new users is to ask questions of the form "How can I iterate over my df to do X?". Showing code that calls iterrows()
while doing something inside a for
loop. Here is why. A new user to the library who has not been introduced to the concept of vectorization will likely envision the code that solves their problem as iterating over their data to do something. Not knowing how to iterate over a DataFrame, the first thing they do is Google it and end up here, at this question. They then see the accepted answer telling them how to, and they close their eyes and run this code without ever first questioning if iteration is not the right thing to do.
The aim of this answer is to help new users understand that iteration is not necessarily the solution to every problem, and that better, faster and more idiomatic solutions could exist, and that it is worth investing time in exploring them. I'm not trying to start a war of iteration vs. vectorization, but I want new users to be informed when developing solutions to their problems with this library.
You could use a UITextField with the leftView property and then set the enabled
property to NO
Or use a UIButton and setImage:forControlState
Watch out for pitfalls. If the field Name
in Table1
contain Nulls you are in for surprises.
Better is:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT ISNULL(name ,'')
FROM table1)
Indeed there is.
chmod a+x
is relative to the current state and just sets the x
flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.
chmod 755
, however, sets the mask as written: rwxr-xr-x
, no matter how it was before. It is equivalent to chmod u=rwx,go=rx
.
SET ROWCOUNT 1000;
DELETE FROM [MyTable] WHERE .....
SQL Workbench has such a feature.
After running a query, right click on the query results and choose "Copy Data As SQL > SQL Insert"
You can access multiple columns by passing a list of column indices to dataFrame.ix.
For example:
>>> df = pandas.DataFrame({
'a': np.random.rand(5),
'b': np.random.rand(5),
'c': np.random.rand(5),
'd': np.random.rand(5)
})
>>> df
a b c d
0 0.705718 0.414073 0.007040 0.889579
1 0.198005 0.520747 0.827818 0.366271
2 0.974552 0.667484 0.056246 0.524306
3 0.512126 0.775926 0.837896 0.955200
4 0.793203 0.686405 0.401596 0.544421
>>> df.ix[:,[1,3]]
b d
0 0.414073 0.889579
1 0.520747 0.366271
2 0.667484 0.524306
3 0.775926 0.955200
4 0.686405 0.544421
If you just need to await
to avoid nesting code:
let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
json = data;
done();
}));
Object oriented version
$dateObject = new DateTime( $date_raw );
print('Next Date ' . $dateObject->sub( new DateInterval('P1D') )->format('Y-m-d');
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
new_vector.assign(old_vector.begin(),old_vector.end()); // Method 1
new_vector = old_vector; // Method 2
It depends what you're going for. I believe the closest thing JS has to print is:
document.write( produceMessage() );
However, it may be more prudent to place the value inside a span or a div of your choosing like:
document.getElementById("mySpanId").innerHTML = produceMessage();
Kotlin version with infix function
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
Then you can write:
view1 below view2
Or you can call it as a normal function:
view1.below(view2)