You can call the button_click event by simply passing the arguments to it:
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click(sender, args);
}
For Oracle, it is also LENGTH instead of LEN
SELECT MAX(LENGTH(Desc)) FROM table_name
Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.
If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.
The reason why you don't see such practice is quite subjective and cannot have a definite answer, because I have seen many of the code which uses your mentioned way rather than iterator
style code.
Following can be reasons of people not considering vector.size()
way of looping:
size()
every time in the loop
condition. However either it's a non-issue or it can be trivially
fixedstd::for_each()
over the for
loop itselfstd::vector
to other one (e.g.
map
, list
) will also demand the change of the looping mechanism,
because not every container support size()
style of loopingC++11 provides a good facility to move through the containers. That is called "range based for loop" (or "enhanced for loop" in Java).
With little code you can traverse through the full (mandatory!) std::vector
:
vector<int> vi;
...
for(int i : vi)
cout << "i = " << i << endl;
For the case I met, I found there are missing modules after make. So I did the following:
try this:
public int getIndexOfMin(List<Float> data) {
float min = Float.MAX_VALUE;
int index = -1;
for (int i = 0; i < data.size(); i++) {
Float f = data.get(i);
if (Float.compare(f.floatValue(), min) < 0) {
min = f.floatValue();
index = i;
}
}
return index;
}
IIS_IUSRS group has prominence only if you are using ApplicationPool Identity. Even though you have this group looks empty at run time IIS adds to this group to run a worker process according to microsoft literature.
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
You could copy the XAMPP shortcut into "Local Disk C /users/YourUserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Start-up"...
This will make the control panel start up with the computer. Then if you were to select the configuration in the top right hand corner of the control panel you can make Apache and MySQL auto start... This is a quite long-winded get around, but it works for Windows 10.
Instead of
null,
use CustomerDTO customers =
new CustomerDTO()`;
CustomerDTO customer = null;
private static List<Author> getAllAuthors() {
initConnection();
List<Author> authors = new ArrayList<Author>();
Author author = new Author();
try {
stmt = (Statement) conn.createStatement();
String str = "SELECT * FROM author";
rs = (ResultSet) stmt.executeQuery(str);
while (rs.next()) {
int id = rs.getInt("nAuthorId");
String name = rs.getString("cAuthorName");
author.setnAuthorId(id);
author.setcAuthorName(name);
authors.add(author);
System.out.println(author.getnAuthorId() + " - " + author.getcAuthorName());
}
rs.close();
closeConnection();
} catch (Exception e) {
System.out.println(e);
}
return authors;
}
Your if
statement is always false and T
gets initialized only if a condition is met, so the code doesn't reach the point where T
gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.
Try:
def temp_sky(lreq, breq):
T = <some_default_value> # None is often a good pick
for line in tfile:
data = line.split()
if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:
T = data[2]
return T
Define a constructor in the abstract class which sets the field so that the concrete implementations are per the specification required to call/override the constructor.
E.g.
public abstract class AbstractTable {
protected String name;
public AbstractTable(String name) {
this.name = name;
}
}
When you extend AbstractTable
, the class won't compile until you add a constructor which calls super("somename")
.
public class ConcreteTable extends AbstractTable {
private static final String NAME = "concreteTable";
public ConcreteTable() {
super(NAME);
}
}
This way the implementors are required to set name
. This way you can also do (null)checks in the constructor of the abstract class to make it more robust. E.g:
public AbstractTable(String name) {
if (name == null) throw new NullPointerException("Name may not be null");
this.name = name;
}
For the allowed characters you can use
^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$
to validate a complete string that should consist of only allowed characters. Note that -
is at the end (because otherwise it'd be a range) and a few characters are escaped.
For the invalid characters you can use
[<>'"/;`%]
to check for them.
To combine both into a single regex you can use
^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])
but you'd need a regex engine that allows lookahead.
More correct create DTO for API queries, for example entityDTO:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityDto> getAll() { return entityService.getAllEntities(); }
But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getOneParameterMap() { return ResponseEntity.status(HttpStatus.CREATED).body( Collections.singletonMap("key", "value")); }
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getSomeParameters() { return ResponseEntity.status(HttpStatus.OK).body(Map.of( "key-1", "value-1", "key-2", "value-2", "key-3", "value-3")); }
You would need to use a reinterpret_cast<>
as the two types you are casting between are unrelated to each other.
I got this error when there was not enough disk space to restore Db. Cleaning some space solved it.
All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray
, and you need to retain the shape of array.
I have compare just two, but it will retain the shape of ndarray
. I have used the array with 1 million entries for comparison. Here I use square function. I am presenting the general case for n dimensional array. For two dimensional just make iter
for 2D.
import numpy, time
def A(e):
return e * e
def timeit():
y = numpy.arange(1000000)
now = time.time()
numpy.array([A(x) for x in y.reshape(-1)]).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.fromiter((A(x) for x in y.reshape(-1)), y.dtype).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.square(y)
print(time.time() - now)
Output
>>> timeit()
1.162431240081787 # list comprehension and then building numpy array
1.0775556564331055 # from numpy.fromiter
0.002948284149169922 # using inbuilt function
here you can clearly see numpy.fromiter
user square function, use any of your choice. If you function is dependent on i, j
that is indices of array, iterate on size of array like for ind in range(arr.size)
, use numpy.unravel_index
to get i, j, ..
based on your 1D index and shape of array numpy.unravel_index
This answers is inspired by my answer on other question here
This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer
element in my case didn't show. I added a position: relative
which worked.
We can use git mv command. Example below , if we renamed file abcDEF.js to abcdef.js then we can run the following command from terminal
git mv -f .\abcDEF.js .\abcdef.js
I was also having this issue of "You have mail" coming up every time I started Terminal.
What I discovered is this.
Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".
You can access the mail by simply using the command
mail
This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use
t
This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow
key.
If you want to jump to the end of the message, use the
spacebar
If you want to abort viewing the message, use
q
To view the next message in the queue use
n
... assuming there's more than one message.
NOTE: You need to use these commands at the mail ?
command prompt. They won't work whilst you are in the process of viewing a message. Hitting n
whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q
to quit from that, or hit spacebar
to jump to the end of the message, and then at the ?
prompt, hit n
.
Viewing the content of the messages in this way may help you identify what attempted to send the message(s).
You can also view a specific message by just inputting its number at the ?
prompt. 3
, for instance, will show you the content of the third message (if there are that many in there).
Use the d
command (at the ?
command prompt )
d [message number]
To delete each message when you are done looking at them. For example, d 2
will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7
. Or you can delete a range of messages with (for example), d 3-10
.
You can find the message numbers in the list of messages mail shows you.
To delete all the messages, from the mail prompt (?
) use the command d *
.
As per a comment on this post, you will need to use q
to quit mail, which also saves any changes.
If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):
cat /var/mail/<username>
And, if you wish to delete the emails all in one hit, use this command
sudo rm /var/mail/<username>
In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.
What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.
If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail
command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:
sudo rm /var/mail/YOURUSERNAME
Or Check https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html
As of October 2017:
1. In the list of your projects, click on the project you want to delete;
2. In the left sidebar, click on the 'Setting' button;
3. Locate the 'Advanced settings' section and click on the related 'Expand' button;
4. At the bottom you'll find the 'Remove Project' button, click it;
5. Type the name of the project inside the text input and Confirm.
Me Too
How about using some beautiful markup with Kotlin and Anko -
import org.jetbrains.anko.*
override fun onCreate(savedInstanceState: Bundle?) {
title = "Created with Beautiful Markup"
super.onCreate(savedInstanceState)
verticalLayout {
editText {
hint = buildSpanned {
append("Italic, ", Italic)
append("highlighted", backgroundColor(0xFFFFFF00.toInt()))
append(", Bold", Bold)
}
}
}
}
FORCE_INDEX
is going to be deprecated after MySQL 8:
Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in
a future release of MySQL, and at some time thereafter to be removed altogether.
https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
You should be using JOIN_INDEX
, GROUP_INDEX
, ORDER_INDEX
, and INDEX
instead, for v8.
This simply means that either tree
, tree[otu]
, or tree[otu][0]
evaluates to None
, and as such is not subscriptable. Most likely tree[otu]
or tree[otu][0]
. Track it down with some simple debugging like this:
def Ancestors (otu,tree):
try:
tree[otu][0][0]
except TypeError:
print otu, tre[otu]
raise
#etc...
or pdb
This is not so much an answer to your original question as to one of the queries you had in the body of your question.
A little preamble, so that my naming doesn't seem strange:
import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )
As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:
ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')
You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:
ax.xaxis.major.formatter._useMathText = True
This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:
rc('text', usetex=True)
Apache PDF Box can convert PDFs to jpg,bmp,wbmp,png, and gif.
The library even comes with a command line utility called PDFToImage to do this.
If you download the source code and look at the PDFToImage class you should be able to figure out how to use PDF Box to convert PDFs to images from your own Java code.
Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.
Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/
Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html
I had the same problem so i create ImageView that draw behind status bar API 19+
Set custom image behind Status Bar gist.github.com
public static void setTransparent(Activity activity, int imageRes) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
// set flags
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
// get root content of system window
//ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
// rootView.setFitsSystemWindows(true);
// rootView.setClipToPadding(true);
ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
if (contentView.getChildCount() > 1) {
contentView.removeViewAt(1);
}
// get status bar height
int res = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
int height = 0;
if (res != 0)
height = activity.getResources().getDimensionPixelSize(res);
// create new imageview and set resource id
ImageView image = new ImageView(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
image.setLayoutParams(params);
image.setImageResource(imageRes);
image.setScaleType(ScaleType.MATRIX);
// add image view to content view
contentView.addView(image);
// rootView.setFitsSystemWindows(true);
}
You can use following command -
LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))
This will return NULL if your string1
is Numeric
your query would be -
select * from tablename
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null
for safety we should not use self signed certificates in our implementation. However, when it comes to development often we have to use trial environments which got self-signed certs. I tried to fix this issue programmatically in my code and I fail. However, by adding the cert to the jre trust-store fixed my issue. Please find below steps,
Download the site cert,
Copy the certificate(ex:cert_file.cer) into the directory $JAVA_HOME\Jre\Lib\Security
Open CMD in Administrator and change the directory to $JAVA_HOME\Jre\Lib\Security
Import the certificate to a trust store using below command,
keytool -import -alias ca -file cert_file.cer -keystore cacerts -storepass changeit
If you got a error saying keytool is not recognizable please refer this.
Type yes like below
Trust this certificate: [Yes]
Update
If your app server is jboss try adding below system property
System.setProperty("org.jboss.security.ignoreHttpsHost","true");
Hope this helps!
If you used Mac OS and Brew try this:
mkdir /usr/local/etc/my.cnf.d
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
I'm assuming Windows if you're using WAMP. Composer likely is just using the PHP set in your path: How to access PHP with the Command Line on Windows?
You should be able to change the path to PHP using the same instructions.
Otherwise, composer is just a PHAR file, you can download the PHAR and execute it using any PHP:
C:\full\path\to\php.exe C:\full\path\to\composer.phar install
I've have the same problem like this, but using my own server. Maybe APACHE is allowing only limited connection to the same server. I'm increasing the max_connection and KeepAlive setting. So far so good.
If you want to know what impact has single object context for WPF / WinForm application check this article. It is about NHibernate Session but the idea is same.
Edit:
When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.
Any changes made to the entity are not persisted until you call SaveChanges
on the context. You can do changes in multiple entities and store them at once. This is called Unit of Work pattern. You can't selectively say which modified attached entity you want to save.
Combine these two patterns and you will see some interesting effects. You have only one instance of entity for the whole application. Any changes to the entity affect the whole application even if changes are not yet persisted (commited). In the most times this is not what you want. Suppose that you have an edit form in WPF application. You are working with the entity and you decice to cancel complex editation (changing values, adding related entities, removing other related entities, etc.). But the entity is already modified in shared context. What will you do? Hint: I don't know about any CancelChanges or UndoChanges on ObjectContext
.
I think we don't have to discuss server scenario. Simply sharing single entity among multiple HTTP requests or Web service calls makes your application useless. Any request can just trigger SaveChanges
and save partial data from another request because you are sharing single unit of work among all of them. This will also have another problem - context and any manipulation with entities in the context or a database connection used by the context is not thread safe.
Even for a readonly application a global context is not a good choice because you probably want fresh data each time you query the application.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
replace session_start();
with @session_start();
in your code
Now this can be achieved with the JSONLib library:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
If (and only if) you use the overloaded toString(int indentationFactor)
method and not the standard toString()
method.
I have verified this on the following version of the API:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
if you want both always a return value but never a null value you can combine count with coalesce :
select count(field1), coalesce(field1,'any_other_default_value') from table;
that because count, will force mysql to always return a value (0 if there is no values to count) and coalesce will force mysql to always put a value that is not null
Can't install RMagick 2.13.2. in ubuntu 17.10
My decision
- sudo apt-get purge imagemagick libmagickcore-dev libmagickwand-dev
- sudo apt-get autoremove
- sudo rm /usr/bin/Magick-config
- sudo apt-get install imagemagick libmagickwand-dev
Version is required to correctly specify the path to the configuration
- cd /usr/lib/x86_64-linux-gnu
- View version ImageMagick, my version ImageMagick - 6.9.7.
- cd ImageMagick-6.9.7/
- ls
- look at the name of the directory bin-q16 or bin-Q16
Creating a link to the config
sudo ln -s /usr/lib/x86_64-linux-gnu/ImageMagick-version/bin-directory/Magick-config /usr/bin/Magick-config
Creating for my version ImageMagick
- sudo ln -s /usr/lib/x86_64-linux-gnu/ImageMagick-6.9.7/bin-q16/Magick-config /usr/bin/Magick-config
- bundle
This worked for me:
static void ClearLine(){
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
In order to not have the Cannot recover key
exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.
Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy
. Setting that to unlimited
with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty()
or via the java.security
file. The java.security
file could also be appended to by adding -Djava.security.properties=my_security.properties
to the command to start the program as detailed here.
Since JDK 8u161 unlimited cryptography is enabled by default.
In my.cnf file check below 2 steps.
check this value -
old_passwords=0;
it should be 0.
check this also-
[mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure
[mysqld] section should be like this.
I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.
I find it better and easier than downloading and pasting DLLs.
Suppose I have an SVG which looks like this:
And I want to put it in a div and make it fill the div responsively. My way of doing it is as follows:
First I open the SVG file in an application like inkscape. In File->Document Properties I set the width of the document to 800px and and the height to 600px (you can choose other sizes). Then I fit the SVG into this document.
Then I save this file as a new SVG file and get the path data from this file. Now in HTML the code that does the magic is as follows:
<div id="containerId">
<svg
id="svgId"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
version="1.1"
x="0"
y="0"
width="100%"
height="100%"
viewBox="0 0 800 600"
preserveAspectRatio="none">
<path d="m0 0v600h800v-600h-75.07031l-431 597.9707-292.445315-223.99609 269.548825-373.97461h-271.0332z" fill="#f00"/>
</svg>
</div>
Note that width and height of SVG are both set to 100%, since we want it to fill the container vertically and horizontally ,but width and height of the viewBox are the same as the width and height of the document in inkscape which is 800px X 600px. The next thing you need to do is set the preserveAspectRatio to "none". If you need to have more information on this attribute here's a good link. And that's all there is to it.
One more thing is that this code works on almost all the major browsers even the old ones but on some versions of android and ios you need to use some javascrip/jQuery code to keep it consistent. I use the following in document ready and resize functions:
$('#svgId').css({
'width': $('#containerId').width() + 'px',
'height': $('#containerId').height() + 'px'
});
Hope it helps!
\n
is a line break. /n
is not.
use of \n
with
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with
<br />
or<br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
kings
garden
Note Make sure you're echoing/printing
\n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
Notice: I do update this answer as I find better solutions. I also keep the old answers for future reference as long as they remain related. Latest and best answer comes first.
Directives in angularjs are very powerful, but it takes time to comprehend which processes lie behind them.
While creating directives, angularjs allows you to create an isolated scope with some bindings to the parent scope. These bindings are specified by the attribute you attach the element in DOM and how you define scope property in the directive definition object.
There are 3 types of binding options which you can define in scope and you write those as prefixes related attribute.
angular.module("myApp", []).directive("myDirective", function () {
return {
restrict: "A",
scope: {
text: "@myText",
twoWayBind: "=myTwoWayBind",
oneWayBind: "&myOneWayBind"
}
};
}).controller("myController", function ($scope) {
$scope.foo = {name: "Umur"};
$scope.bar = "qwe";
});
HTML
<div ng-controller="myController">
<div my-directive my-text="hello {{ bar }}" my-two-way-bind="foo" my-one-way-bind="bar">
</div>
</div>
In that case, in the scope of directive (whether it's in linking function or controller), we can access these properties like this:
/* Directive scope */
in: $scope.text
out: "hello qwe"
// this would automatically update the changes of value in digest
// this is always string as dom attributes values are always strings
in: $scope.twoWayBind
out: {name:"Umur"}
// this would automatically update the changes of value in digest
// changes in this will be reflected in parent scope
// in directive's scope
in: $scope.twoWayBind.name = "John"
//in parent scope
in: $scope.foo.name
out: "John"
in: $scope.oneWayBind() // notice the function call, this binding is read only
out: "qwe"
// any changes here will not reflect in parent, as this only a getter .
Since this answer got accepted, but has some issues, I'm going to update it to a better one. Apparently, $parse
is a service which does not lie in properties of the current scope, which means it only takes angular expressions and cannot reach scope.
{{
,}}
expressions are compiled while angularjs initiating which means when we try to access them in our directives postlink
method, they are already compiled. ({{1+1}}
is 2
in directive already).
This is how you would want to use:
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function ($parse) {
return function (scope, element, attr) {
element.val("value=" + $parse(attr.myDirective)(scope));
};
});
function MyCtrl($scope) {
$scope.aaa = 3432;
}?
.
<div ng-controller="MyCtrl">
<input my-directive="123">
<input my-directive="1+1">
<input my-directive="'1+1'">
<input my-directive="aaa">
</div>????????
One thing you should notice here is that, if you want set the value string, you should wrap it in quotes. (See 3rd input)
Here is the fiddle to play with: http://jsfiddle.net/neuTA/6/
I'm not removing this for folks who can be misled like me, note that using $eval
is perfectly fine the correct way to do it, but $parse
has a different behavior, you probably won't need this to use in most of the cases.
The way to do it is, once again, using scope.$eval
. Not only it compiles the angular expression, it has also access to the current scope's properties.
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function () {
return function (scope, element, attr) {
element.val("value = "+ scope.$eval(attr.value));
}
});
function MyCtrl($scope) {
}?
What you are missing was $eval
.
http://docs.angularjs.org/api/ng.$rootScope.Scope#$eval
Executes the expression on the current scope returning the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating angular expressions.
in Swift 4.2 it is a property now.
override var prefersStatusBarHidden: Bool {
return true
}
CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.
You need to capture from regex. search
for the pattern, if found, retrieve the string using group(index)
. Assuming valid checks are performed:
>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1) # group(1) will return the 1st capture (stuff within the brackets).
# group(0) will returned the entire matched text.
'my_user_name'
Python is case sensitive and needs proper indentation. You need to use lowercase "if", indent your conditions properly and the code has a bug. proceed
will evaluate to y
Try to look at http.get and response headers.
var http = require("http");
var options = {
host: 'stackoverflow.com',
port: 80,
path: '/'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
for(var item in res.headers) {
console.log(item + ": " + res.headers[item]);
}
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Start with:
find . -name '*.log.*.zip' -a -mtime +1
You may not need a regex, try:
find . -name '*.log.*-*-*.zip' -a -mtime +1
You will want the +1 in order to match 1, 2, 3 ...
The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.
If you want to gain access to the whole the error body, do it as shown below:
async function login(reqBody) {
try {
let res = await Axios({
method: 'post',
url: 'https://myApi.com/path/to/endpoint',
data: reqBody
});
let data = res.data;
return data;
} catch (error) {
console.log(error.response); // this is the main part. Use the response property from the error object
return error.response;
}
}
Having the following XML:
<node>Text1<subnode/>text2</node>
How do I select either the first or the second text node via XPath?
Use:
/node/text()
This selects all text-node children of the top element (named "node") of the XML document.
/node/text()[1]
This selects the first text-node child of the top element (named "node") of the XML document.
/node/text()[2]
This selects the second text-node child of the top element (named "node") of the XML document.
/node/text()[someInteger]
This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:
/node/text()[position() = someInteger]
If you are using version 1
Recaptcha.reload();
If you are using version 2
grecaptcha.reset();
How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)
q = (x > 0)? 1 + (x - 1)/y: (x / y);
I reduced y/y
to one, eliminating the term x + y - 1
and with it any chance of overflow.
I avoid x - 1
wrapping around when x
is an unsigned type and contains zero.
For signed x
, negative and zero still combine into a single case.
Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.
You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.
Here's a complete example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__APPLE__)
# define COMMON_DIGEST_FOR_OPENSSL
# include <CommonCrypto/CommonDigest.h>
# define SHA1 CC_SHA1
#else
# include <openssl/md5.h>
#endif
char *str2md5(const char *str, int length) {
int n;
MD5_CTX c;
unsigned char digest[16];
char *out = (char*)malloc(33);
MD5_Init(&c);
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
for (n = 0; n < 16; ++n) {
snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
}
return out;
}
int main(int argc, char **argv) {
char *output = str2md5("hello", strlen("hello"));
printf("%s\n", output);
free(output);
return 0;
}
Right Click the Project in Solution Explorer and click Manage NuGet Packages
Search for MySql.Data package, when you find it click on Install
Here is the sample controller which connects to MySql database using the mysql package. We mainly make use of MySqlConnection connection object.
public class HomeController : Controller
{
public ActionResult Index()
{
List<employeemodel> employees = new List<employeemodel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT EmployeeId, Name, Country FROM Employees";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
employees.Add(new EmployeeModel
{
EmployeeId = Convert.ToInt32(sdr["EmployeeId"]),
Name = sdr["Name"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
}
return View(employees);
}
}
You can use push and pull to change column ordering. You pull one column and push the other on large devices:
<div class="row">
<div class="col-lg-6 col-md-6 col-lg-pull-6">elements 1</div>
<div class="col-lg-6 col-md-6 col-lg-push-6">
<div>
elements 2
</div>
</div>
</div>
And for those occasions when a yum install colordiff
or an apt-get install colordiff
is not an option due to some insane constraint beyond your immediate control, or you're just feeling crazy, you can re-invent the wheel with a line of sed:
sed 's/^-/\x1b[41m-/;s/^+/\x1b[42m+/;s/^@/\x1b[34m@/;s/$/\x1b[0m/'
Throw that in a shell script and pipe unified diff output through it.
It makes hunk markers blue and highlights new/old filenames and added/removed lines in green and red background, respectively.1 And it will make trailing space2 changes more readily apparent than colordiff can.
1 Incidentally, the reason for highlighting the filenames the same as the modified lines is that to correctly differentiate between the filenames and the modified lines requires properly parsing the diff format, which is not something to tackle with a regex. Highlighting them the same works "well enough" visually and makes the problem trivial. That said, there are some interesting subtleties.
2 But not trailing tabs. Apparently tabs don't get their background set, at least in my xterm. It does make tab vs space changes stand out a bit though.
In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:
Install ThinBackup on both the source and the target Jenkins servers
Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)
On the source Jenkins, go to ThinBackup ? Backup Now
Copy from Jenkins source backup directory to the Jenkins target backup directory
On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.
If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.
If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity>
to false, and restart Jenkins.
The technique from Making something both a C identifier and a string? can be used here.
As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.
enumFactory.h:
// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,
// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;
// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;
/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
enum EnumType { \
ENUM_DEF(ENUM_VALUE) \
}; \
const char *GetString(EnumType dummy); \
EnumType Get##EnumType##Value(const char *string); \
/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
const char *GetString(EnumType value) \
{ \
switch(value) \
{ \
ENUM_DEF(ENUM_CASE) \
default: return ""; /* handle input error */ \
} \
} \
EnumType Get##EnumType##Value(const char *str) \
{ \
ENUM_DEF(ENUM_STRCMP) \
return (EnumType)0; /* handle input error */ \
} \
someEnum.h:
#include "enumFactory.h"
#define SOME_ENUM(XX) \
XX(FirstValue,) \
XX(SecondValue,) \
XX(SomeOtherValue,=50) \
XX(OneMoreValue,=100) \
DECLARE_ENUM(SomeEnum,SOME_ENUM)
someEnum.cpp:
#include "someEnum.h"
DEFINE_ENUM(SomeEnum,SOME_ENUM)
The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.
While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.
In Chrome, window.onload is different from <body onload="">
, whereas they are the same in both Firefox(version 35.0) and IE (version 11).
You could explore that by the following snippet:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--import css here-->
<!--import js scripts here-->
<script language="javascript">
function bodyOnloadHandler() {
console.log("body onload");
}
window.onload = function(e) {
console.log("window loaded");
};
</script>
</head>
<body onload="bodyOnloadHandler()">
Page contents go here.
</body>
</html>
And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()
" in the consoles of IE & FF, you will see:
"function onload(event) { bodyOnloadHandler() }"
which means that the assignment "window.onload = function(e)..." is overwritten.
By using JavaScript: document.getElementById("myBtn").click();
String path = System.getProperty("user.dir")+"/config.xml";
File f=new File(path);
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
You would need to say which version of Ant and which JVM version.
You can run ant -v
to see which settings Ant is using as per the doc
Ant 1.8* requires JDK 1.4 or higher.
The 'Unsupported major.minor version 51.0' means somewhere code was compiled for a version of the JDK, and that you are trying to run those classes under an older version of the JDK. (see here)
May be it is the problem of using len()
for an integer value.
does not posses the len attribute in Python.
Error as:I will give u an example:
number= 1
print(len(num))
Instead of use ths,
data = [1,2,3,4]
print(len(data))
If your database is small enough (or if you add enough memory) your database will effectively run in memory since it your data will be cached after the first request.
Changing the database table definitions to use the memory engine is probably more complicated than you need.
If you have enough memory to load the tables into memory with the MEMORY
engine, you have enough to tune the innodb settings to cache everything anyway.
Not sure but I think this was a question not about the height of a 'multiple' type of select element but a drop-down type of select element. I have come across times when the drop-down looks squashed and does not show clearly the selected value. Undoubtedly it has to do with CSS style info in use on the page. The only way to stop it is either change the CSS (which would likely affect the whole page or parts of it in ways you don't want affected) or use style info in the select element itself to override the CSS that's clobbering it. Example:
<select name="myselect" id="myselect" style="font-size:15px; height:30px">
<option value="someval">somedescr</option>
...
</select>
Hope this helps.
You can assign a variable inside of if
statement, but you must declare it first
A slight tweak to the function returns the next word from a start point in the entry CREATE FUNCTION [dbo].[GetWord] ( @value varchar(max) , @startLocation int ) RETURNS varchar(max) AS BEGIN SET @value = LTRIM(RTRIM(@Value)) SELECT @startLocation = CASE WHEN @startLocation > Len(@value) THEN LEN(@value) ELSE @startLocation END SELECT @value = CASE WHEN @startLocation > 1 THEN LTRIM(RTRIM(RIGHT(@value, LEN(@value) - @startLocation))) ELSE @value END RETURN CASE CHARINDEX(' ', @value, 1) WHEN 0 THEN @value ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END END GO SELECT dbo.GetWord(NULL, 1) SELECT dbo.GetWord('', 1) SELECT dbo.GetWord('abc', 1) SELECT dbo.GetWord('abc def', 4) SELECT dbo.GetWord('abc def ghi', 20)
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
ui router make your life easier! You can add it to you AngularJS application via injecting it into your applications...
ng-route
comes as part of the core AngularJS, so it's simpler and gives you fewer options...
Look at here to understand ng-route better: https://docs.angularjs.org/api/ngRoute
Also when using it, don't forget to use: ngView ..
ng-ui-router is different but:
https://github.com/angular-ui/ui-router but gives you more options....
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with ()
brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:
SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);
Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:
Both the basic source and basic execution character sets shall have the following members:
[...]
the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
[...]
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.
There is no library function to do it for a single char
, you would need to build a string first:
int digit_to_int(char d)
{
char str[2];
str[0] = d;
str[1] = '\0';
return (int) strtol(str, NULL, 10);
}
You could also use the atoi()
function to do the conversion, once you have a string, but strtol()
is better and safer.
As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.
You will need to sort your object before mapping over them. And it can be done easily with a sort()
function with a custom comparator definition like
var obj = [...this.state.data];
obj.sort((a,b) => a.timeM - b.timeM);
obj.map((item, i) => (<div key={i}> {item.matchID}
{item.timeM} {item.description}</div>))
YES<input type="radio" name="group1" id="sal" value="YES" >
NO<input type="radio" name="group1" id="sal1" value="NO" >
<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">
In Mac terminal (we can launch Mac Terminal by searching in spotlight search Command + space) Now, use the command:
pip3 install pandas
As I'm using Python Version 3 I need to use pip3 install pandas.
If you are using python version 2 than use Command:
pip install pandas
Make sure pip is already installed in the device
Leveraging the power of java.util.Optional#map()
:
List<Car> requiredCars = cars.stream()
.filter (car ->
Optional.ofNullable(car)
.map(Car::getName)
.map(name -> name.startsWith("M"))
.orElse(false) // what to do if either car or getName() yields null? false will filter out the element
)
.collect(Collectors.toList())
;
In Entity Framework Core 2.1 we can use Query Types as Yuriy N suggested.
A more detailed article on how to use them can be found here
The most straight forward approach according to the article's examples would be:
1.We have for example the following entity Models to manage publications
public class Magazine
{
public int MagazineId { get; set; }
public string Name { get; set; }
public string Publisher { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public int ArticleId { get; set; }
public string Title { get; set; }
public int MagazineId { get; set; }
public DateTime PublishDate { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
}
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public List<Article> Articles { get; set; }
}
2.We have a view called AuthorArticleCounts, defined to return the name and number of articles an author has written
SELECT
a.AuthorName,
Count(r.ArticleId) as ArticleCount
from Authors a
JOIN Articles r on r.AuthorId = a.AuthorId
GROUP BY a.AuthorName
3.We go and create a model to be used for the View
public class AuthorArticleCount
{
public string AuthorName { get; private set; }
public int ArticleCount { get; private set; }
}
4.We create after that a DbQuery property in my DbContext to consume the view results inside the Model
public DbQuery<AuthorArticleCount> AuthorArticleCounts{get;set;}
4.1. You might need to override OnModelCreating() and set up the View especially if you have different view name than your Class.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Query<AuthorArticleCount>().ToView("AuthorArticleCount");
}
5.Finally we can easily get the results of the View like this.
var results=_context.AuthorArticleCounts.ToList();
UPDATE According to ssougnez's comment
It's worth noting that DbQuery won't be/is not supported anymore in EF Core 3.0. See here
The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your sys.path
, and it should just work as the official fcntl module.
Try using this module for development/testing purposes only in windows.
def fcntl(fd, op, arg=0):
return 0
def ioctl(fd, op, arg=0, mutable_flag=True):
if mutable_flag:
return 0
else:
return ""
def flock(fd, op):
return
def lockf(fd, operation, length=0, start=0, whence=0):
return
buf.delete(0, buf.length());
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
to fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the
deserialized type so that it is a normal .NET type (e.g. not a primitive type like
integer, not a collection type like an array or List) that can be deserialized from a
JSON object.`
The whole message indicates that it is possible to serialize to a List object, but the input must be a JSON list. This means that your JSON must contain
"accounts" : [{<AccountObjectData}, {<AccountObjectData>}...],
Where AccountObject data is JSON representing your Account object or your Badge object
What it seems to be getting currently is
"accounts":{"github":"sergiotapia"}
Where accounts is a JSON object (denoted by curly braces), not an array of JSON objects (arrays are denoted by brackets), which is what you want. Try
"accounts" : [{"github":"sergiotapia"}]
Try HostingEnvironment.MapPath
, which is static
.
See this SO question for confirmation that HostingEnvironment.MapPath
returns the same value as Server.MapPath
: What is the difference between Server.MapPath and HostingEnvironment.MapPath?
Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...
return new System.Web.Http.Results.ResponseMessageResult(
new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
});
See nashawn's answer for JsonContent.
Associative Arrays in JavaScript don't really work the same as they do in other languages. for each
statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push
method:
jsArr = [];
for (var i = 1; i <= 10; i++) {
jsArr.push('example ' + 1);
}
Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].
Using d.Keys()(i)
method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).
Here is an analogue of Scripting.Dictionary
called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html
Dim oDict As clsTrickHashTable
Sub aaa()
Set oDict = New clsTrickHashTable
oDict.Add "a", "aaa"
oDict.Add "b", "bbb"
For i = 0 To oDict.Count - 1
Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
Next
End Sub
For the Javadoc tag @see
, you don't need to use @link
; Javadoc will create a link for you. Try
@see com.my.package.Class#method()
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.
You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:
clean:
@if [ "test" = "test" ]; then\
echo "Hello world";\
fi
Note that the closing ";" and "\" are necessary.
Datepicker in german (Deutsch):
$.datepicker.regional['de'] = {
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['Son','Mon','Die','Mit','Don','Fre','Sam'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
firstDay: 1};
$.datepicker.setDefaults($.datepicker.regional['de']);
You need to include your pipe in module declaration:
declarations: [ UsersPipe ],
providers: [UsersPipe]
I had to delete %TEMP%\pip-build On Windows 7
Below solution works from API level 14+
Backgrounding ComponentCallbacks2 — Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the onTrimMemory method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.
Foregrounding ActivityLifecycleCallbacks — We can use this to detect foreground by overriding onActivityResumed and keeping track of the current application state (Foreground/Background).
Create our interface that will be implemented by a custom Application class
interface LifecycleDelegate {
fun onAppBackgrounded()
fun onAppForegrounded()
}
Create a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2 and override onActivityResumed and onTrimMemory methods
// Take an instance of our lifecycleHandler as a constructor parameter
class AppLifecycleHandler(private val lifecycleDelegate: LifecycleDelegate)
: Application.ActivityLifecycleCallbacks, ComponentCallbacks2 // <-- Implement these
{
private var appInForeground = false
// Override from Application.ActivityLifecycleCallbacks
override fun onActivityResumed(p0: Activity?) {
if (!appInForeground) {
appInForeground = true
lifecycleDelegate.onAppForegrounded()
}
}
// Override from ComponentCallbacks2
override fun onTrimMemory(level: Int) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
// lifecycleDelegate instance was passed in on the constructor
lifecycleDelegate.onAppBackgrounded()
}
}
}
Now all we need to do is have our custom Application class implement our LifecycleDelegate interface and register.
class App : Application(), LifeCycleDelegate {
override fun onCreate() {
super.onCreate()
val lifeCycleHandler = AppLifecycleHandler(this)
registerLifecycleHandler(lifeCycleHandler)
}
override fun onAppBackgrounded() {
Log.d("Awww", "App in background")
}
override fun onAppForegrounded() {
Log.d("Yeeey", "App in foreground")
}
private fun registerLifecycleHandler(lifeCycleHandler: AppLifecycleHandler) {
registerActivityLifecycleCallbacks(lifeCycleHandler)
registerComponentCallbacks(lifeCycleHandler)
}
}
In Manifest set the CustomApplicationClass
<application
android:name=".App"
If you just want to open up the webpage, I think less is more in this case:
import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL
class BrowseURL{
public static void main(String args[]) throws Exception{
// Create Desktop object
Desktop d=Desktop.getDesktop();
// Browse a URL, say google.com
d.browse(new URI("http://google.com"));
}
}
}
-[NSString initWithData:encoding]
will return nil
if the specified encoding doesn't match the data's encoding.
Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).
Seen from a non-PHP guru perspective, this should do exactly what us desired to:
<style>
[name$='pdf'] { width:100%; height: auto;}
</style>
I had the very same problem and then I realized that programming in NodeJS is actually different than Python or Java as its based on JavaScript. I'll try to use simple concepts as there may be a few new folks that would be interested or may come to this question.
Let's look at the following code :
var http = require('http'); // (1)
exports.handler = function(event, context) {
console.log('start request to ' + event.url)
http.get(event.url, // (2)
function(res) { //(3)
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
console.log('end request to ' + event.url); //(4)
}
Whenever you make a call to a method in http package (1) , it is created as event and this event gets it separate event. The 'get' function (2) is actually the starting point of this separate event.
Now, the function at (3) will be executing in a separate event, and your code will continue it executing path and will straight jump to (4) and finish it off, because there is nothing more to do.
But the event fired at (2) is still executing somewhere and it will take its own sweet time to finish. Pretty bizarre, right ?. Well, No it is not. This is how NodeJS works and its pretty important you wrap your head around this concept. This is the place where JavaScript Promises come to help.
You can read more about JavaScript Promises here. In a nutshell, you would need a JavaScript Promise to keep the execution of code inline and will not spawn new / extra threads.
Most of the common NodeJS packages have a Promised version of their API available, but there are other approaches like BlueBirdJS that address the similar problem.
The code that you had written above can be loosely re-written as follows.
'use strict';
console.log('Loading function');
var rp = require('request-promise');
exports.handler = (event, context, callback) => {
var options = {
uri: 'https://httpbin.org/ip',
method: 'POST',
body: {
},
json: true
};
rp(options).then(function (parsedBody) {
console.log(parsedBody);
})
.catch(function (err) {
// POST failed...
console.log(err);
});
context.done(null);
};
Please note that the above code will not work directly if you will import it in AWS Lambda. For Lambda, you will need to package the modules with the code base too.
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.
Basically, when you have something like:
<form onsubmit="return callSomeFunction();"></form>
or
<a href="#" onclick="return callSomeFunction();"></a>`
and callSomeFunction()
returns true, then the form
or a
will submit, otherwise it won't.
Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.
You can always see the console in a different window by opening the Organiser, clicking on the Devices tab, choosing your device and selecting it's console.
Of course, this doesn't work for the simulator :(
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
If your question was this -- Select ename, dname FROM emp, dept without using joins..
Then, I would do this...
SELECT ename, (SELECT dname
FROM dept
WHERE dept.deptno=emp.deptno)dname
FROM EMP
Output:
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
ENAME DNAME
---------- --------------
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows selected.
All you need to do is
android:isScrollContainer="true"
source: http://www.davidwparker.com/2011/08/25/android-fixing-window-resize-and-scrolling/
Use GSONBuilder with setPrettyPrinting and disableHtml for nice output.
String json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().
create().toJson(outputList );
fileOut.println(json);
If you are just interested in growing, you can update the width
to scrollWidth
, whenever the content of the input
element changes.
document.querySelectorAll('input[type="text"]').forEach(function(node) {
node.onchange = node.oninput = function() {
node.style.width = node.scrollWidth+'px';
};
});
But this will not shrink the element.
$(window).bind("load", function() {
// write your code here
});
I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.
I used the same data frame as @Brian:
data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600,
1317798000, 1317884400, 1317970800, 1318057200,
1318143600, 1318230000, 1318316400, 1318402800,
1318489200, 1318575600, 1318662000, 1318748400,
1318834800, 1318921200, 1319007600, 1319094000),
class = c("POSIXct", "POSIXt"), tzone = ""),
TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71,
25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18,
25.19, 24.19, 27.65, 23.92),
TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72,
20.45, 19.42, 19.97, 19.61),
TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82,
14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95,
17.55, 15.21, 14.22, 16.42)),
.Names = c("month", "TempMax", "TempMed", "TempMin"),
row.names = c(NA, 20L), class = "data.frame")
In my case, I generate my.cols
and my.names
dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.
my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names
And here is the plot:
p <- ggplot(data, aes(x = month))
for (i in 1:3){
p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour =
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("",
breaks = as.character(my.names),
values = my.cols)
p
I had the same exact problem, expect for Windows OS.
For me, running
npm install -g nodemon --save-dev
(note the -g) worked.
Maybe somebody else who has this problem on Windows will have the same solution.
This is a pithy solution.
import datetime
todayDate = datetime.date.today()
if todayDate.day > 25:
todayDate += datetime.timedelta(7)
print todayDate.replace(day=1)
One thing to note with the original code example is that using timedelta(30)
will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.
It does includes boundaries.
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
You can delete IDEA configuration directory to reset everything to the defaults. If you want to reset the editor Colors&Fonts, then just switch the scheme to Default.
swift 4
if you don't want use storyboard, this might be help.
you can add table view and set properties in a closure:
lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.backgroundColor = UIColor(named: Palette.secondaryLight.rawValue)
tableView.rowHeight = 68
tableView.separatorStyle = .none
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
then add in subview and set constraints.
ok. I solved it
SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
`page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct (CASE WHEN page_pages.funnel_id != 0 then page_pages.funnel_id ELSE NULL END ) ) as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE smart_projects.status != 0
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
GROUP BY `smart_projects`.`project_id`
ORDER BY `title` DESC
Agreeing with r-dub, keep it in source control, but to me, the real benefit is this:
collaboration in identical environments (disregarding the windohs and linux/mac stuff). Before Gemfile.lock, the next dude to install the project might see all kinds of confusing errors, blaming himself, but he was just that lucky guy getting the next version of super gem, breaking existing dependencies.
Worse, this happened on the servers, getting untested version unless being disciplined and install exact version. Gemfile.lock makes this explicit, and it will explicitly tell you that your versions are different.
Note: remember to group stuff, as :development and :test
You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[]
in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer
(expecting Serializable
, and using ObjectOutputStream
). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.
I guess you can copy the entire package and make use of it.
A simple method:
$array = array_values(array_unique($array, SORT_REGULAR));
private int compareLists(List<String> list1, List<String> list2){
Collections.sort(list1);
Collections.sort(list2);
int maxIteration = 0;
if(list1.size() == list2.size() || list1.size() < list2.size()){
maxIteration = list1.size();
} else {
maxIteration = list2.size();
}
for (int index = 0; index < maxIteration; index++) {
int result = list1.get(index).compareTo(list2.get(index));
if (result == 0) {
continue;
} else {
return result;
}
}
return list1.size() - list2.size();
}
There can be more than one main method in a single program. But JVM will always calls String[] argument main() method. Other method's will act as a Overloaded method. These overloaded method's we have to call explicitly.
I always have to check my cheatsheet :-)
Step 1: right-click on the top of putty window and select 'Change settings'.
Step 2: type the name of the session and save.
That's it!. Enjoy!
VMware experiences a lot of clock drift. This Google search for 'vmware clock drift' links to several articles.
The first hit may be the most useful for you: http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues
In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b
contains of an independent subexpression a / b
, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double
. a / b
is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.
One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading
void foo(int);
void foo(double);
void (*p)(double) = &foo; // automatically selects `foo(fouble)`
This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.
This is similar to Emilie's answer however since you asked specifically how to convert the NSRange
to Range<String.Index>
you would do something like this:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let start = advance(textField.text.startIndex, range.location)
let end = advance(start, range.length)
let swiftRange = Range<String.Index>(start: start, end: end)
...
}
This started happening to my site after I enabled namespace and custom Open Graph actions and objects. Once you enable it, you lose support for standard object types such as bar, or in my case article. (or it's possible Facebook may have deprecated certain types, I'm not 100% sure) When no supported type is specified, Facebook defaults to website.
To fix this what you need to do is go into your app dashboard, select your app, then go to the Open Graph section. Under "Object Types", define your own types, such as "bar."
Next you will have to change your meta tags to look like this:
<meta property="og:type" content="your_namespace:your_object_type" />
If you click on "Get Code" next to the object type in the dashboard, Facebook will provide you with an example of meta tags to use.
Add this as a first line in the HEAD section of your HTML template
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
You can use this extension method for enumerables containing more complex types:
IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
var knownKeys = new HashSet<TKey>();
return source.Where(element => knownKeys.Add(keySelector(element)));
}
SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
Didn't quite see this variation in the answers yet. I had an additional constraint where I needed, given an initial seed, to select the same set of rows each time.
For MS SQL:
Minimum example:
select top 10 percent *
from table_name
order by rand(checksum(*))
Normalized execution time: 1.00
NewId() example:
select top 10 percent *
from table_name
order by newid()
Normalized execution time: 1.02
NewId()
is insignificantly slower than rand(checksum(*))
, so you may not want to use it against large record sets.
Selection with Initial Seed:
declare @seed int
set @seed = Year(getdate()) * month(getdate()) /* any other initial seed here */
select top 10 percent *
from table_name
order by rand(checksum(*) % @seed) /* any other math function here */
If you need to select the same set given a seed, this seems to work.
If lists always have the same structure, as in the example, then a simpler solution is
mapply(c, first, second, SIMPLIFY=FALSE)
If you don't mind installing a package for it, you can use json-tricks:
pip install json-tricks
After that you just need to import dump(s)
from json_tricks
instead of json, and it'll usually work:
from json_tricks import dumps
json_str = dumps(cls_instance, indent=4)
which'll give
{
"__instance_type__": [
"module_name.test_class",
"MyTestCls"
],
"attributes": {
"attr": "val",
"dct_attr": {
"hello": 42
}
}
}
And that's basically it!
This will work great in general. There are some exceptions, e.g. if special things happen in __new__
, or more metaclass magic is going on.
Obviously loading also works (otherwise what's the point):
from json_tricks import loads
json_str = loads(json_str)
This does assume that module_name.test_class.MyTestCls
can be imported and hasn't changed in non-compatible ways. You'll get back an instance, not some dictionary or something, and it should be an identical copy to the one you dumped.
If you want to customize how something gets (de)serialized, you can add special methods to your class, like so:
class CustomEncodeCls:
def __init__(self):
self.relevant = 42
self.irrelevant = 37
def __json_encode__(self):
# should return primitive, serializable types like dict, list, int, string, float...
return {'relevant': self.relevant}
def __json_decode__(self, **attrs):
# should initialize all properties; note that __init__ is not called implicitly
self.relevant = attrs['relevant']
self.irrelevant = 12
which serializes only part of the attributes parameters, as an example.
And as a free bonus, you get (de)serialization of numpy arrays, date & times, ordered maps, as well as the ability to include comments in json.
Disclaimer: I created json_tricks, because I had the same problem as you.
You can do this as:
WITH abc AS( select
FROM ...)
, XYZ AS(select
From abc ....) /*This one uses "abc" multiple times*/
Select
From XYZ.... /*using abc, XYZ multiple times*/
One easy way to map that country name that you have to an int
to be used in the setImageResource
method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
Being DialogFragment
a wrapper for the Dialog
class, you should set a theme to your base Dialog
to get the animation you want:
public class CustomDialogFragment extends DialogFragment implements OnEditorActionListener
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// Set a theme on the dialog builder constructor!
AlertDialog.Builder builder =
new AlertDialog.Builder( getActivity(), R.style.MyCustomTheme );
builder
.setTitle( "Your title" )
.setMessage( "Your message" )
.setPositiveButton( "OK" , new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
return builder.create();
}
}
Then you just need to define the theme that will include your desired animation. In styles.xml add your custom theme:
<style name="MyCustomTheme" parent="@android:style/Theme.Panel">
<item name="android:windowAnimationStyle">@style/MyAnimation.Window</item>
</style>
<style name="MyAnimation.Window" parent="@android:style/Animation.Activity">
<item name="android:windowEnterAnimation">@anim/anim_in</item>
<item name="android:windowExitAnimation">@anim/anim_out</item>
</style>
Now add the animation files in the res/anim folder:
( the android:pivotY
is the key )
anim_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:interpolator="@android:anim/linear_interpolator"
android:fromXScale="0.0"
android:toXScale="1.0"
android:fromYScale="0.0"
android:toYScale="1.0"
android:fillAfter="false"
android:startOffset="200"
android:duration="200"
android:pivotX = "50%"
android:pivotY = "-90%"
/>
<translate
android:fromYDelta="50%"
android:toYDelta="0"
android:startOffset="200"
android:duration="200"
/>
</set>
anim_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:interpolator="@android:anim/linear_interpolator"
android:fromXScale="1.0"
android:toXScale="0.0"
android:fromYScale="1.0"
android:toYScale="0.0"
android:fillAfter="false"
android:duration="200"
android:pivotX = "50%"
android:pivotY = "-90%"
/>
<translate
android:fromYDelta="0"
android:toYDelta="50%"
android:duration="200"
/>
</set>
Finally, the tricky thing here is to get your animation grow from the center of each row. I suppose the row is filling the screen horizontally so, on one hand the android:pivotX
value will be static. On the other hand, you can't modify the android:pivotY
value programmatically.
What I suggest is, you define several animations each of which having a different percentage value on the android:pivotY
attribute (and several themes referencing those animations). Then, when the user taps the row, calculate the Y position in percentage of the row on the screen. Knowing the position in percentage, assign a theme to your dialog that has the appropriate android:pivotY
value.
It is not a perfect solution but could do the trick for you. If you don't like the result, then I would suggest forgetting the DialogFragment
and animating a simple View
growing from the exact center of the row.
Good luck!
Note that all of the example that use
<repository>...</respository>
require outer
<repositories>...</repositories>
enclosing tags. It's not clear from some of the examples.
For ES6/ES2015 you can import directly like:
// example.json
{
"name": "testing"
}
// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
If you use typescript, you may declare json module like:
// tying.d.ts
declare module "*.json" {
const value: any;
export default value;
}
Assuming lengths of portfolio and index are the same:
matrix = []
for i in range(len(portfolio)):
matrix.append([portfolio[i], index[i]])
Or a one-liner using list comprehension:
matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
Use for a date three days ago:
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);
Check the DATE_ADD documentation.
Or you can use:
WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )
Hopefully this helps:
>>> seta = set('1234')
>>> listb = ['a','b','c']
>>> seta.union(listb)
set(['a', 'c', 'b', '1', '3', '2', '4'])
>>> seta
set(['1', '3', '2', '4'])
>>> seta = seta.union(listb)
>>> seta
set(['a', 'c', 'b', '1', '3', '2', '4'])
Write your event handler declaration like this:
<a href="#" onclick="myFunc(event,1,2,3)">click</a>
Then your "myFunc()" function can access the event.
The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:
theAnchor.onclick = new Function("event", theOnclickString);
(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.
The proper way is mvn package
if you did things correctly for the core part of your build then there should be no need to install your packages in the local repository.
In addition if you use Travis you can "cache" your dependencies because it will not touch your $HOME.m2/repository
if you use package for your own project.
In practicality if you even attempt to do a mvn site
you usually need to do a mvn install
before. There's just too many bugs with either site
or it's numerous poorly maintained plugins.
[HttpPost]
public string MyMethod([FromBody]JObject data)
{
Customer customer = data["customerData"].ToObject<Customer>();
Product product = data["productData"].ToObject<Product>();
Employee employee = data["employeeData"].ToObject<Employee>();
//... other class....
}
using referance
using Newtonsoft.Json.Linq;
Use Request for JQuery Ajax
var customer = {
"Name": "jhon",
"Id": 1,
};
var product = {
"Name": "table",
"CategoryId": 5,
"Count": 100
};
var employee = {
"Name": "Fatih",
"Id": 4,
};
var myData = {};
myData.customerData = customer;
myData.productData = product;
myData.employeeData = employee;
$.ajax({
type: 'POST',
async: true,
dataType: "json",
url: "Your Url",
data: myData,
success: function (data) {
console.log("Response Data ?");
console.log(data);
},
error: function (err) {
console.log(err);
}
});
Extract substring between two string (excluding this two strings)
let allText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum";
let textBefore = "five centuries,";
let textAfter = "electronic typesetting";
var regExp = new RegExp(`(?<=${textBefore}\\s)(.+?)(?=\\s+${textAfter})`, "g");
var results = regExp.exec(allText);
if (results && results.length > 1) {
console.log(results[0]);
}
Express makes this kind of stuff really intuitive. The syntax looks like below :
var app = require('express').createServer();
app.get("/string", function(req, res) {
var strings = ["rad", "bla", "ska"]
var n = Math.floor(Math.random() * strings.length)
res.send(strings[n])
})
app.listen(8001)
If you're using jQuery on the client side you can do something like this:
$.get("/string", function(string) {
alert(string)
})
It's '
.
As noted by msanders, this is actually XML and XHTML but not defined in HTML4, so I guess use the '
in that case. I stand corrected.
This is my approach, based on amir's answer, but it doesn't let any word make the string longer than the limit, by using strrpos() with a negative offset.
Simple but works. I'm using the same syntax as in Laravel's str_limit() helper function, in case you want to use it on a non-Laravel project.
function str_limit($value, $limit = 100, $end = '...')
{
$limit = $limit - mb_strlen($end); // Take into account $end string into the limit
$valuelen = mb_strlen($value);
return $limit < $valuelen ? mb_substr($value, 0, mb_strrpos($value, ' ', $limit - $valuelen)) . $end : $value;
}
If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF
trick:
DECLARE @CodeNameString varchar(100)
SELECT
@CodeNameString = STUFF( (SELECT ',' + CodeName
FROM dbo.AccountCodes
ORDER BY Sort
FOR XML PATH('')),
1, 1, '')
The FOR XML PATH('')
basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3
etc.) and the STUFF
puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.
UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <
, >
or &
, then my current solution will in fact encode those into <
, >
, and &
.
If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.
This technique is now deprecated.
This used to tell Google how to index the page.
https://developers.google.com/webmasters/ajax-crawling/
This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value
, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value
to fetch a non-AJAX version of the contents.
I was seeing this error on Chrome
while I was testing my code locally. I switched to Firefox
and I am not seeing the error any more. Maybe switching to another browser is a quick fix.
If you are using the solution given in first answer, then make sure you add img.crossOrigin = "Anonymous";
just after you declare the img
variable (for eg. var img = new Image();
).
To do this in C you can use the sysctl(3) family of functions:
int count;
size_t count_len = sizeof(count);
sysctlbyname("hw.logicalcpu", &count, &count_len, NULL, 0);
fprintf(stderr,"you have %i cpu cores", count);
Interesting values to use in place of "hw.logicalcpu", which counts cores, are:
hw.physicalcpu - The number of physical processors available in the current power management mode.
hw.physicalcpu_max - The maximum number of physical processors that could be available this boot.
hw.logicalcpu - The number of logical processors available in the current power management mode.
hw.logicalcpu_max - The maximum number of logical processors that could be available this boot.
String[] errorSoon = new String[n];
With n being how many strings it needs to hold.
You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.
You can also cross reference repos:
githubuser/repository#xxx
xxx being the issue number
Try this (subquery):
SELECT * FROM terms WHERE id IN
(SELECT term_id FROM terms_relation WHERE taxonomy = "categ")
Or you can try this (JOIN):
SELECT t.* FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
If you want to receive all fields from two tables:
SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at
FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
Just because this is what I got when I Googled this error, my problem was that I had
if (value < other.value)
return -1;
else if (value >= other.value)
return 1;
else
return 0;
the value >= other.value
should (obviously) actually be value > other.value
so that you can actually return 0 with equal objects.
@Bass Jobsen and @ElwoodP attempted to answer this question in reverse--giving the outer margins the same DOUBLE size as the gutters. The OP (and me, as well) was searching for a way to have a SINGLE size gutter in all places. Here are the correct CSS adjustments to do so:
.row {
margin-left: -7px;
margin-right: -7px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
padding-left: 7px;
padding-right: 7px;
}
.container {
padding-left: 14px;
padding-right: 14px;
}
This leaves a 14px
gutter and outside margin in all places.
With Underscore.js A few ways with Underscore can be done. Here is one of them. Checking if the array is already unique.
function isNameUnique(values){
return _.uniq(values, function(v){ return v.name }).length == values.length
}
With vanilla JavaScript By checking if there is no recurring names in the array.
function isNameUnique(values){
var names = values.map(function(v){ return v.name });
return !names.some(function(v){
return names.filter(function(w){ return w==v }).length>1
});
}
import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)
Output: "This is a test"
In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:
if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi
For a real installation script, you'd probably want to be sure that type
doesn't return successfully in the case when there is an alias foobar
. In bash you could do something like this:
if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi
Just because you have a project inside the workspace directory doesn't mean Eclipse opens it or even sees it automatically. You must use File - Import - General - Import existing project into workspace to have your project in Eclipse.
Actually it depends on what shell you use, however most shells have similar bindings. The bindings you are referring to (e.g. Ctrl+A and Ctrl+E) are bindings you will find in many other programs and they are used for ages, BTW also work in most UI apps.
Here's a look of default bindings for Bash:
Most Important Bash Keyboard Shortcuts
Please also note that you can customize them. You need to create a file, name as you wish, I named mine .bash_key_bindings and put it into my home directory. There you can set some general bash options and you can also set key bindings. To make sure they are applied, you need to modify a file named ".bashrc" that bash reads in upon start-up (you must create it, if it does not exist) and make the following call there:
bind -f ~/.bash_key_bindings
~ means home directory in bash, as stated above, you can name the file as you like and also place it where you like as long as you feed the right path+name to bind.
Let me show you some excerpts of my .bash_key_bindings file:
set meta-flag on
set input-meta on
set output-meta on
set convert-meta off
set show-all-if-ambiguous on
set bell-style none
set print-completions-horizontally off
These just set a couple of options (e.g. disable the bell; this can be all looked up on the bash webpage).
"A": self-insert
"B": self-insert
"C": self-insert
"D": self-insert
"E": self-insert
"F": self-insert
"G": self-insert
"H": self-insert
"I": self-insert
"J": self-insert
These make sure that the characters alone just do nothing but making sure the character is "typed" (they insert themselves on the shell).
"\C-dW": kill-word
"\C-dL": kill-line
"\C-dw": backward-kill-word
"\C-dl": backward-kill-line
"\C-da": kill-line
This is quite interesting. If I hit Ctrl+D alone (I selected d for delete), nothing happens. But if I then type a lower case w, the word to the left of the cursor is deleted. If I type an upper case, however, the word to the right of the cursor is killed. Same goes for l and L regarding the whole line starting from the cursor. If I type an "a", the whole line is actually deleted (everything before and after the cursor).
I placed jumping one word forward on Ctrl+F and one word backward on Ctrl+B
"\C-f": forward-word
"\C-b": backward-word
As you can see, you can make a shortcut, that leads to an action immediately, or you can make one, that just inits a character sequence and then you have to type one (or more) characters to cause an action to take place as shown in the example further above.
So if you are not happy with the default bindings, feel free to customize them as you like. Here's a link to the bash manual for more information.
I have tried this problem in pure JS. I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value
// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];
//sort the given array
inpArr.sort(function(a, b){
return a-b;
});
var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
//check previous and next value
if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
finalArr.push(inpArr[i]);
}
}
console.log(finalArr);
Fixed positioning is supposed to define everything in relation to the viewport, so position:fixed
is always going to do that. Try using position:relative
on the child div instead.
(I realize you might need the fixed positioning for other reasons, but if so - you can't really make the width match it's parent with out JS without inherit
)
In addition to the other answers, there is a big benefit to using the DisplayAttribute
when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.
Also, you can let MVC generate the templates for you by using Html.EditorForModel()
and it will generate the correct label for you.
Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.
If you are returning a complex json object you need to modify you success function of your auto-complete as follows.
$.ajax({
url: "/Employees/SearchEmployees",
dataType: "json",
data: {
searchText: request.term
},
success: function (data) {
response($.map(data.employees, function (item) {
return {
label: item.name,
value: item.id
};
}));
}
});
Visual Editor is a good choice.
It generates very clean code, with no "layout" files beside of your sourcen using a simple but convenient pattern. It's very easy to patch the generated code and directly see the result. There are some stability problems (some times, the preview window does not refresh anymore...), but nothing that a "clean Project" can't fix...
A simple solution that works with Ubuntu, but may fix the problem on windows too:
Just call
pip install --upgrade pip
Booleans are nothing but integers only, they are just type casted values like...
typedef signed char BOOL;
#define YES (BOOL)1
#define NO (BOOL)0
BOOL value = YES;
NSLog(@"Bool value: %d",value);
If output is 1,YES otherwise NO
For what Joel Coehorn suggested, have you already tried the utility named tcping. I know this is something you are not doing programmatically. It is a standalone executable which allows you to ping every specified time interval. It is not in C# though. Also..I am not sure If this would work If the target machine has firewall..hmmm..
[I am kinda new to this site and mistakenly added this as a comment, now added this as an answer. Let me know If this can be done here as I have duplicate comments (as comment and as an answer) here. I can not delete comments here.]
This comes a little close.
.box
{
-webkit-box-shadow: inset -1px 10px 5px -3px #000000;
box-shadow: inset -1px 10px 5px -3px #000000;
}
There is a simpler solution
if (inputDate.getDate() === todayDate.getDate()) {
// do stuff
}
like that you don't loose the time attached to inputDate
if any
python 3.2
>>>> from itertools import chain
>>>> eg=sorted(list(set(list(chain(*eg)))), reverse=True)
[7, 6, 5, 4, 3, 2, 1]
##### eg contain 2 list within a list. so if you want to use set() function
you should flatten the list like [1, 2, 3, 4, 4, 5, 6, 7]
>>> res= list(chain(*eg)) # [1, 2, 3, 4, 4, 5, 6, 7]
>>> res1= set(res) # [1, 2, 3, 4, 5, 6, 7]
>>> res1= sorted(res1,reverse=True)
I found my realm file by issuing this command in Terminal:
sudo find / -name "*.realm"
.
Hope this helps!
res/drawable/day_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/dayselectionunselected"
android:state_checked="false"/>
<item android:drawable="@drawable/daysselectionselected"
android:state_checked="true"/>
<item android:drawable="@drawable/dayselectionunselected"/>
</selector>
res/layout/my_layout.xml
<CheckBox
android:id="@+id/check"
android:layout_width="39dp"
android:layout_height="39dp"
android:background="@drawable/day_selector"
android:button="@null"
android:gravity="center"
android:text="S"
android:textColor="@color/black"
android:textSize="12sp" />
Another option is to add another tag with flex: auto
style in between your tags that you want to fill in the remaining space.
https://jsfiddle.net/tsey5qu4/
The HTML:
<div class="parent">
<div class="left">Left</div>
<div class="fill-remaining-space"></div>
<div class="right">Right</div>
</div>
The CSS:
.fill-remaining-space {
flex: auto;
}
This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.
chmod 777 /var/run/docker.sock
This worked like a charm
Execute the following on your terminal to get the latest stable version:
sudo gem install cocoapods
Add --pre
to get the latest pre release:
sudo gem install cocoapods --pre
If you originally installed the cocoapods gem using sudo
, you should use that command again.
Later on, when you're actively using CocoaPods by installing pods, you will be notified when new versions become available with a CocoaPods X.X.X is now available, please update message.
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=@fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("@Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +""
part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=@fName"
oCmd.Parameters.AddWithValue("@fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null
.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person>
.
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
SELECT P.*
FROM primary_table P
LEFT JOIN secondary_table S on P.id = S.p_id
WHERE S.p_id IS NULL
grep -n "YOUR SEARCH STRING" * > output-file
The -n
will print the line number and the >
will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe |
for example:
grep -n "test" * | grep -v "mytest" > output-file
will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v
) - and will redirect the result to an output file.
A few good grep-tips can be found on this post
try to use the array_unique()
this elminates duplicated data inside the list of your arrays..
I was looking into the explanation " If you only override hashCode then when you call myMap.put(first,someValue)
it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(first,someOtherValue)
it should replace first with second as per the Map Documentation because they are equal (according to our definition)." :
I think 2nd time when we are adding in myMap
then it should be the 'second' object like myMap.put(second,someOtherValue)
Assuming you only have WHERE clauses on table A create a stored procedure thus:
SELECT Id, Name From tableA WHERE ...
SELECT tableA.Id AS ParentId, Somecolumn
FROM tableA INNER JOIN tableB on TableA.Id = TableB.F_Id
WHERE ...
Then fill a DataSet ds with it. Then
ds.Relations.Add("foo", ds.Tables[0].Columns("Id"), ds.Tables[1].Columns("ParentId"));
Finally you can add a repeater in the page that puts the commas for every line
<asp:DataList ID="Subcategories" DataKeyField="ParentCatId"
DataSource='<%# Container.DataItem.CreateChildView("foo") %>' RepeatColumns="1"
RepeatDirection="Horizontal" ItemStyle-HorizontalAlign="left" ItemStyle-VerticalAlign="top"
runat="server" >
In this way you will do it client side but with only one query, passing minimal data between database and frontend
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)
I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.
Hope that helps.
Place this line before the closing script tag,writing from memory:
window.onload = GetTimeZoneOffset;
i think the question is how to call the javascript function on pageload
Explicitly mention the ubuntu version in the docker file which you are trying to RUN,
FROM ubuntu:14.04
Dont use like FROM ubuntu:Latest
. This resolved my above "Cannot Start Container: stat /bin/sh: no such file or directory" issue