Yes. You can have a span
within a span
. Your problem stems from something else.
You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:
<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video
id="Video"
class="video-js vjs-default-skin vjs-big-play-centered"
controls
preload="none"
width="auto"
height="auto"
poster="poster.jpg"
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>
A function written in Kotlin:
/**
* Delete the notification
*/
fun delete(context: Context, notificationId: Int) =
with(NotificationManagerCompat.from(context)) {
cancel(notificationId)
}
Or shorter:
fun delete(context: Context, notificationId: Int) = NotificationManagerCompat.from(context).cancel(notificationId)
The jQueryUI provides a extension to animate
function that allows you to animate css class.
edit: Example here
There are also methods to add/remove/toggle class which you might also be interested in.
A lot of answers only explain how to do the search.
To view the results look for a search tab (normally docked at the bottom of the screen):
After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.
All you need to do is declare a variable as public static datatype 'variableName'
in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.
Example of such is,
Form1
public static int quantity;
quantity=TextBox1.text; \\Value which you want to pass
Form2
TextBox2.Text=Form1.quantity;\\ Data will be placed in TextBox2
I found this while googling the issue with android licences when installing Flutter.
For Linux, update Your ~/.bashrc
(or other shell config) file by adding this line at the end:
JAVA_HOME=/usr/local/android-studio/jre
Note: I installed Android studio by following the official installation guide for Linux (link).
For Windows, use the android studio's path to the jre
directory and update the environment variable with the right value.
Then, run flutter doctor --android-licenses
and press y
to review the licences which are not accepted.
Press y
for each of the licences. It will ask Accept? (y/N):
at the end of the license file.
After You accept all unaccepted licences, You should see:
All SDK package licenses accepted
Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name
argument of the scale_
function to NULL
, i.e.
scale_fill_discrete(name = NULL)
(kudos to @pascal for a comment on another thread)
I've made some research and found that Richard Watson's solution is fastest in most cases. That's the table with results of every solution in the post (except those use Regex because it throws exceptions while parsing string like "test{test")
Name | Short/char | Long/char | Short/short| Long/short | Long/long |
Inspite | 134| 1853| 95| 1146| 671|
LukeH_1 | 346| 4490| N/A| N/A| N/A|
LukeH_2 | 152| 1569| 197| 2425| 2171|
Bobwienholt | 230| 3269| N/A| N/A| N/A|
Richard Watson| 33| 298| 146| 737| 543|
StefanosKargas| N/A| N/A| 681| 11884| 12486|
You can see that in case of finding number of occurences of short substrings (1-5 characters) in short string(10-50 characters) the original algorithm is preferred.
Also, for multicharacter substring you should use the following code (based on Richard Watson's solution)
int count = 0, n = 0;
if(substring != "")
{
while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
{
n += substring.Length;
++count;
}
}
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
Here is the complete xml with gradient, stoke & circular shape.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<!-- You can use gradient with below attributes-->
<gradient
android:angle="90"
android:centerColor="#555994"
android:endColor="#b5b6d2"
android:startColor="#555994"
android:type="linear" />
<!-- You can omit below tag if you don't need stroke -->
<stroke android:color="#3b91d7" android:width="5dp"/>
<!-- Set the same value for both width and height to get a circular shape -->
<size android:width="200dp" android:height="200dp"/>
<!--if you need only a single color filled shape-->
<solid android:color="#e42828"/>
</shape>
Like so
DECLARE @t INT=1
SELECT CASE
WHEN @t>0 THEN
CASE
WHEN @t=1 THEN 'one'
ELSE 'not one'
END
ELSE 'less than one'
END
EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.
I would use invisible recaptcha. Then on your button use a tag like " formname='yourformname' " to specify which form is to be submitted and hide a submit form input.
The advantage of this is it allows for you to keep the html5 form validation intact, one recaptcha, but multiple button interfaces. Just capture the "captcha" input value for the token key generated by recaptcha.
<script src="https://www.google.com/recaptcha/api.js" async defer ></script>
<div class="g-recaptcha" data-sitekey="yours" data-callback="onSubmit" data-size="invisible"></div>
<script>
var formanme = ''
$('button').on('click', function () { formname = '#'+$(this).attr('formname');
if ( $(formname)[0].checkValidity() == true) { grecaptcha.execute(); }
else { $(formname).find('input[type="submit"]').click() }
});
var onSubmit = function(token) {
$(formname).append("<input type='hidden' name='captcha' value='"+token+"' />");
$(formname).find('input[type="submit"]').click()
};
</script>
I find this FAR simpler and easier to manage.
If you are using Eclipse you can move files to and from the SD Card through the Android Perspective (it is called DDMS in Eclipse). Just select the Emulator in the left part of the screen and then choose the File Explorer tab. Above the list with your files should be two symbols, one with an arrow pointing at a phone, clicking this will allow you to choose a file to move to phone memory.
For me, the problem was the Start page -- it was downloading content and causing Visual Studio to hang.
The only solution for me was to:
devenv.exe /safemode
Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY
tells the OS to recreate the service after it has enough memory and call onStartCommand()
again with a null intent. START_NOT_STICKY
tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT
that tells the OS to recreate the service and redeliver the same intent to onStartCommand()
.
This article by Dianne Hackborn explained the background of this a lot better than the official documentation.
Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html
The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:
START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.
START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.
My friend Kien and I have improved upon an earlier version of an ORM that he had written prior to PHP 5.3. We have essentially ported over Ruby on Rails' Active Record to PHP. It is still lacking some key features we want such as transactions, composite primary key support, a few more adapters (only MySQL and SQLite 3 work right now). But, we are very close to finishing this stuff up. You can take a look at PHP ActiveRecord with PHP 5.3.
"Add a reference to MySql.Data.dll" means you need to add a library reference to the downloaded connector. The IDE will link the database connection library with your application when it compiles.
I downloaded the binary (no installer) zip package from the MySQL web site, extracted onto the desktop, and did the following:
using MySql.Data.MySqlClient;
. If you've added the reference correctly, IntelliSense should offer to complete this for you.Try this one:
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
};
This works because you have multiple classes in different jar files. Removing and re-adding the jre lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.
Another way of viewing the full content of the cells in a pandas dataframe is to use IPython's display functions:
from IPython.display import HTML
HTML(df.to_html())
I use LEd Editor with special "Filter" feature. It replaces \"{o} with ö and vice versa in its own editor, while maintaining original \"{o} in tex files. This makes text easily readable when viewed in LEd Editor and there is no need for special packages. It works with bibliography files too.
I find the accepted answer, and all the others strange, since they pass self
to an abstract class. An abstract class is not instantiated so can't have a self
.
So try this, it works.
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def foo():
"""An abstract method. No need to write pass"""
class Derived(Abstract):
def foo(self):
print('Hooray!')
FOO = Derived()
FOO.foo()
Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.
to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
Get all views from any type of layout
public List<View> getAllViews(ViewGroup layout){
List<View> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
views.add(layout.getChildAt(i));
}
return views;
}
Get all TextView from any type of layout
public List<TextView> getAllTextViews(ViewGroup layout){
List<TextView> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
View v =layout.getChildAt(i);
if(v instanceof TextView){
views.add((TextView)v);
}
}
return views;
}
But why would you use excel when you could do it all online and have your boss check your dynamic link.
We are using this new tool since last week. http://www.burndown-charts.com/
What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...
http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x
Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"
won't work because worksheet functions (when actually used on a worksheet) don't understand Range
or Cell
Try
Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"
\1
in double quotes needs to be escaped. So you want either
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")
or
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')
see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."
That being said, if you just want the result of the match you can do:
"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)
or
"Z_sdsd: sdsd"[/^Z_.*(?=:)/]
Note that the (?=:)
is a non-capturing group so that the :
doesn't show up in your match.
For anyone who wants to run private methods without all the fess and mess. This works with any unit testing framework using nothing but good old Reflection.
public class ReflectionTools
{
// If the class is non-static
public static Object InvokePrivate(Object objectUnderTest, string method, params object[] args)
{
Type t = objectUnderTest.GetType();
return t.InvokeMember(method,
BindingFlags.InvokeMethod |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static,
null,
objectUnderTest,
args);
}
// if the class is static
public static Object InvokePrivate(Type typeOfObjectUnderTest, string method, params object[] args)
{
MemberInfo[] members = typeOfObjectUnderTest.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);
foreach(var member in members)
{
if (member.Name == method)
{
return typeOfObjectUnderTest.InvokeMember(method, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, typeOfObjectUnderTest, args);
}
}
return null;
}
}
Then in your actual tests, you can do something like this:
Assert.AreEqual(
ReflectionTools.InvokePrivate(
typeof(StaticClassOfMethod),
"PrivateMethod"),
"Expected Result");
Assert.AreEqual(
ReflectionTools.InvokePrivate(
new ClassOfMethod(),
"PrivateMethod"),
"Expected Result");
The best would be for HH:MM without taking any risk.
^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
Your first formulation, image_url('logo.png')
, is correct. If the image is found, it will generate the path /assets/logo.png
(plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png
.
The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png
.
If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets
from your project directory and restart the server (webrick, etc.).
If that fails, you can also try just using background-image: url(logo.png);
That will cause your CSS to look for files with the same relative path (which in this case is /assets).
SELECT * INTO table2 FROM table1;
And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:
plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))
Adding this here as it doesn't seem to be here.
Aside from the excellent solution of form.append("blob",blob, filename);
you can also turn the blob into a File
instance:
var blob = new Blob([JSON.stringify([0,1,2])], {type : 'application/json'});
var fileOfBlob = new File([blob], 'aFileName.json');
form.append("upload", fileOfBlob);
Your method doesn't have any callbacks so there is no reason to use .CallBack()
. You can simply return a Task with the desired values using .Returns()
and Task.FromResult, e.g.:
MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.FromResult(someValue));
Update 2014-06-22
Moq 4.2 has two new extension methods to assist with this.
mock.Setup(arg=>arg.DoSomethingAsync())
.ReturnsAsync(someValue);
mock.Setup(arg=>arg.DoSomethingAsync())
.ThrowsAsync(new InvalidOperationException());
Update 2016-05-05
As Seth Flowers mentions in the other answer, ReturnsAsync
is only available for methods that return a Task<T>
. For methods that return only a Task,
.Returns(Task.FromResult(default(object)))
can be used.
As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);
, e.g.:
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.CompletedTask);
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding
attributes are evaluated (along with id
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding
attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException
or ConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState()
or restoreState()
methods and like).
binding
on a bean property is bad practiceRegardless, using binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value
, and perhaps others like styleClass
, disabled
, rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent()
, new SomeComponent()
, getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>
, <h:dataTable>
, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation>
to the backing component (i.e. the component identified by <cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding
attribute like so binding="#{foo}"
and the component is during render response elsewhere in the same view directly as UIComponent
reference available by #{foo}
. Here are several related questions where such a solution is been used in the answer:
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
Just run this command
EXEC sp_columns 'Your Table Name'
Lets say ClassOne
is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
Add views to a UIAlertView like this. In iOS 5 there are some "magic" things that do it for you (but that's all under NDA).
If you really want the runtime type to be util.Date then just do this:
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
Brian.
Assuming two apps TestA and TestB. TestB wants to query if TestA is installed. "TestA" defines the following URL scheme in its info.plist file:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>testA</string>
</array>
</dict>
</array>
The second app "TestB" tries to find out if "TestA" is installed by calling:
[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"TestA://"]];
But this will normally return NO in iOS9 because "TestA" needs to be added to the LSApplicationQueriesSchemes entry in TestB's info.plist file. This is done by adding the following code to TestB's info.plist file:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>TestA</string>
</array>
A working implementation can be found here: https://github.com/gatzsche/LSApplicationQueriesSchemes-Working-Example
Hi the following solve my same problem absolutely (import/export and so on):
Fix Bug Phpmyadmin [plugin_interface.lib.php] + Php7.2 + Ubuntu 16.04
so... under ubuntu 18.04, mysql, php7.2: Terminal:
sudo gedit /usr/share/phpmyadmin/libraries/plugin_interface.lib.php
Find the following line(ctrl+f):
if ($options != null && count($options) > 0) {
it was on line #551 for me
and change for following:
if ($options != null && count((array)$options) > 0) {
ctrl+s for save the changes
and in terminal: ctrl+c for get back promt...
and: sudo systemctl restart apache2
"I think in new php version.It can’t use count() or sizeof() with un array type. Force parameter to array is easy way to solve this bug,..."
Thanks for the original author for the problem solving! I try to share it!
Spring exposes the current HttpServletRequest
object (as well as the current HttpSession
object) through a wrapper object of type ServletRequestAttributes
. This wrapper object is bound to ThreadLocal and is obtained by calling the static
method RequestContextHolder.currentRequestAttributes()
.
ServletRequestAttributes
provides the method getRequest()
to get the current request, getSession()
to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Note that the RequestContextHolder.currentRequestAttributes()
method returns an interface and needs to be typecasted to ServletRequestAttributes
that implements the interface.
Spring Javadoc: RequestContextHolder | ServletRequestAttributes
If you have access to the delegate method you can do this:
[20] pry(main)> class Foo
[20] pry(main)* def self.bar
[20] pry(main)* "foo bar"
[20] pry(main)* end
[20] pry(main)* delegate :bar, to: 'self.class'
[20] pry(main)* end
=> [:bar]
[21] pry(main)> Foo.new.bar
=> "foo bar"
[22] pry(main)> Foo.bar
=> "foo bar"
Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:
[1] pry(main)> class Foo
[1] pry(main)* module AvailableToClassAndInstance
[1] pry(main)* def bar
[1] pry(main)* "foo bar"
[1] pry(main)* end
[1] pry(main)* end
[1] pry(main)* include AvailableToClassAndInstance
[1] pry(main)* extend AvailableToClassAndInstance
[1] pry(main)* end
=> Foo
[2] pry(main)> Foo.new.bar
=> "foo bar"
[3] pry(main)> Foo.bar
=> "foo bar"
A word of caution:
Don't just randomly delegate
everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.
Update your Eclipse ADT Plugin to 22.0 or higher, then go to File | Export
Go to Android now then click on Generate Gradle build files
, then it would generate gradle file for you.
Select your project you want to export
Click on finish now
In Android Studio, close any projects currently open. You should see the Welcome to Android Studio window.
Click Import Project.
Locate the project you exported from Eclipse, expand it, select it and click OK.
Try this one:
#!/bin/bash
psql -U postgres -d database_name -c "SELECT c_defaults FROM user_info WHERE c_uid = 'testuser'"
Or using su
:
#!/bin/bash
su -c "psql -d database_name -c \"SELECT c_defaults FROM user_info WHERE c_uid = 'testuser'\"" postgres
And also sudo
:
#!/bin/bash
sudo -u postgres -H -- psql -d database_name -c "SELECT c_defaults FROM user_info WHERE c_uid = 'testuser'"
If you are using an MSSQL Server 2008 and above, you can perform your SELECT
query to return json by using the FOR JSON AUTO
clause E.G
SELECT name, surname FROM users FOR JSON AUTO
Will return Json as
[{"name": "Jane","surname": "Doe" }, {"name": "Foo","surname": "Samantha" }, ..., {"name": "John", "surname": "boo" }]
Refer to this example taken from - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
Window->Show View->Navigator, should pop up the navigator panel on the left hand side, showing the projects list.
It's probably already open in the workspace, but you may have closed the navigator panel, so it looks like you don't have the project open.
Eclipse using ADT Build v22.0.0-675183 on Linux.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
To prevent the flex items from shrinking, set the flex shrink factor to 0
:
The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.
.boxcontainer .box {
flex-shrink: 0;
}
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
width: 200px;_x000D_
background-color: #EEEEEE;_x000D_
border: 2px solid #DDDDDD;_x000D_
padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
position: relative;_x000D_
left: 0;_x000D_
border: 2px solid #BDC3C7;_x000D_
transition: all 0.4s ease;_x000D_
display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
width: 100%;_x000D_
padding: 1rem;_x000D_
flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
<div class="boxcontainer">_x000D_
<div class="box">_x000D_
First bunch of content._x000D_
</div>_x000D_
<div class="box">_x000D_
Second load of content._x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I had similar issue. I was not able to use value="something"
to display and edit.
I had to use the below command inside my <input>
along withe ng model being declared.
[(ngModel)]=userDataToPass.pinCode
Where I have the list of data in the object userDataToPass
and the item that I need to display and edit is pinCode
.
For the same , I referred to this YouTube video
I know this is an older post, but I'm leaving this for whomever else comes looking in the future.
You can't format line breaks into an option; however, you can use the title attibute to give a mouse-over tooltip to give the full info. Use a short descriptor in the option text and give the full skinny in the title.
<option value="1" title="This is my lengthy explanation of what this selection really means, so since you only see 1 on the drop down list you really know that you're opting to elect me as King of Willywarts! Always be sure to read the fine print!">1</option>
It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:
Sub MSDataShape_AddNewCol()
Dim rs As ADODB.Recordset
Set rs = CreateObject("ADODB.Recordset")
With rs
.ActiveConnection = _
"Provider=MSDataShape;" & _
"Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Tempo\New_Jet_DB.mdb"
.Source = _
"SHAPE {" & _
" SELECT ExistingField" & _
" FROM ExistingTable" & _
" ORDER BY ExistingField" & _
"} APPEND NEW adNumeric(5, 4) AS NewField"
.LockType = adLockBatchOptimistic
.Open
Dim i As Long
For i = 0 To .RecordCount - 1
.Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
.MoveNext
Next
rs.Save "C:\rs.xml", adPersistXML
End With
End Sub
Have you tried doing a full "clean" and then rebuild in Eclipse (Project->Clean...)?
Are you able to compile and run with "javac" and "java" straight from the command line? Does that work properly?
If you right click on your project, go to "Properties" and then go to "Java Build Path", are there any suspicious entries under any of the tabs? This is essentially your CLASSPATH.
In the Eclipse preferences, you may also want to double check the "Installed JREs" section in the "Java" section and make sure it matches what you think it should.
You definitely have either a stale .class file laying around somewhere or you're getting a compile-time/run-time mismatch in the versions of Java you're using.
Loop through object with arrow functions
ES6
Object.keys(myObj).forEach(key => {
console.log(key + ' - ' + myObj[key]) // key - value
})
ES7
Object.entries(myObj).forEach(([key, value]) => {
console.log(key + ' - ' + value) // key - value
})
ES8
Adding to @Paco Zarate's terrific answer above, if you want to transpose a table which has multiple types of columns, then add this to the end of line 39, so it only transposes int
columns:
and C.system_type_id = 56 --56 = type int
Here is the full query that is being changed:
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id(@tableToPivot) and
C.name <> @columnToPivot and C.system_type_id = 56 --56 = type int
for xml path('')), 1, 1, '')
To find other system_type_id
's, run this:
select name, system_type_id from sys.types order by name
The very first alias I made once I started customizing my profile in PowerShell was 'which'.
New-Alias which get-command
To add this to your profile, type this:
"`nNew-Alias which get-command" | add-content $profile
The `n at the start of the last line is to ensure it will start as a new line.
Might be useful to some : check for
pointer-events: none;
In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.
set a reference to the Scripting.Runtime library and then use the FileSystemObject:
Dim fso as New FileSystemObject, aFile as File
if (fso.FileExists("PathToFile")) then
aFile = fso.GetFile("PathToFile")
aFile.Delete
End if
further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,
Names to Avoid
\__double_leading_and_trailing_underscore__ names
(reserved by Python)Naming Convention
CapWords
for class names, but lower_with_under.py
for module names. Although there are many existing modules named CapWords.py
, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO
or from StringIO import StringIO
?")You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
You should be able to "MINUS" or "EXCEPT" depending on the flavor of SQL used by your DBMS.
select * from tableA
minus
select * from tableB
If the query returns no rows then the data is exactly the same.
This answer has 20 upvotes now, but it is not intended as an endorsement of std::valarray
.
In my experience, time is better spent installing and learning to use a full-fledged math library such as Eigen. Valarray has fewer features than the competition, but it isn't more efficient or particularly easier to use.
If you only need a little bit of linear algebra, and you are dead-set against adding anything to your toolchain, then maybe valarray
would fit. But, being stuck unable to express the mathematically correct solution to your problem is a very bad position to be in. Math is relentless and unforgiving. Use the right tool for the job.
The standard library provides std::valarray<double>
. std::vector<>
, suggested by a few others here, is intended as a general-purpose container for objects. valarray
, lesser known because it is more specialized (not using "specialized" as the C++ term), has several advantages:
vector
rounds up to the nearest power of two when allocating, so you can resize it without reallocating every time. (You can still resize a valarray
; it's just still as expensive as realloc()
.)Of course, the advantage over using C is that you don't need to manage memory. The dimensions can reside on the stack, or in a slice object.
std::valarray<double> matrix( row * col ); // no more, no less, than a matrix
matrix[ std::slice( 2, col, row ) ] = pi; // set third column to pi
matrix[ std::slice( 3*row, row, 1 ) ] = e; // set fourth row to e
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
String[] resources = new String[]{
"/", "/home","/pictureCheckCode","/include/**",
"/css/**","/icons/**","/images/**","/js/**","/layer/**"
};
http.authorizeRequests()
.antMatchers(resources).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout().logoutUrl("/404")
.permitAll();
super.configure(http);
}
}
You could use this: http://code.google.com/p/java2word
I implemented this API called Java2Word. with a few lines of code, you can generate one Microsoft Word Document.
Eg.:
IDocument myDoc = new Document2004();
myDoc.getBody().addEle(new Heading1("Heading01"));
myDoc.getBody().addEle(new Paragraph("This is a paragraph...")
There is some examples how to use. Basically you will need one jar file. Let me know if you need any further information how to set it up.
*I wrote this because we had one real necessity in a project. More in my blog:
http ://leonardo-pinho.blogspot.com/2010/07/java2word-word-document-generator-from.html *
cheers Leonardo
Edit : Project in link moved to https://github.com/leonardoanalista/java2word
I couldn't get the accepted answer to work the way I wanted it to (see Farrukh's comment).
I came up with a slightly different solution which also feels more native because it selects the item on mouse button down and then you're able to react to it when the mouse button gets released:
XAML:
<ListView Name="MyListView" ItemsSource={Binding MyItems}>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
<EventSetter Event="PreviewMouseLeftButtonUp" Handler="ListViewItem_PreviewMouseLeftButtonUp" />
</Style>
</ListView.ItemContainerStyle>
Code behind:
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
MyListView.SelectedItems.Clear();
ListViewItem item = sender as ListViewItem;
if (item != null)
{
item.IsSelected = true;
MyListView.SelectedItem = item;
}
}
private void ListViewItem_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
ListViewItem item = sender as ListViewItem;
if (item != null && item.IsSelected)
{
// do stuff
}
}
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
gradle
versiongradle
taskUsing Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
you can simply use this code:
ggplot(yourdatasetname, aes(Position, fill = Name)) +
geom_bar(col = "black", size = 2)
This is some code I use to have a user select one datetimepicker, set the datetime, and have the other datetimepicker add One Minute to that time.
I needed this for a custom medication control....
Anyway, thought it might help someone else since I could not find the answer any where online...
(at least not a complete answer)
Keep in mind that the 60000 added, adds one minute. (60 * 1000 milliseconds)
$('.frdtPicker').datetimepicker({
onClose: function(dateText, inst) {
var endDateTextBox = $('.todtPicker');
if (endDateTextBox.val() != '') {
var testStartDate = new Date(dateText);
var testEndDate = new Date(endDateTextBox.val());
if (testStartDate > testEndDate) {
var testStartDate = new Date(dateText).getTime() + 60000;
var testStartDate2 = new Date(testStartDate);
endDateTextBox.datetimepicker('setDate', (new Date(testStartDate2)));
}
}
else {
var testStartDate = new Date(dateText).getTime() + 60000;
var testStartDate2 = new Date(testStartDate);
endDateTextBox.datetimepicker('setDate', (new Date(testStartDate2)));
}
$('.frdtPicker').val(dateText); //endDateTextBox.val());
},
onSelect: function(selectedDateTime) {
var start = $(this).datetimepicker('getDate');
$('.todtPicker').datetimepicker('option', 'minDate', new Date(start.getTime()));
}
});
If you are getting this error when you run stuffs on automated cluster and you are downloading the stable version of the google chrome every time then you can use the below shell script to download the compatible version of the chrome driver dynamically every time even if the stable version of the chrome gets updated.
%sh
#downloading compatible chrome driver version
#getting the current chrome browser version
**chromeVersion=$(google-chrome --product-version)**
#getting the major version value from the full version
**chromeMajorVersion=${chromeVersion%%.*}**
# setting the base url for getting the release url for the chrome driver
**baseDriverLatestReleaseURL=https://chromedriver.storage.googleapis.com/LATEST_RELEASE_**
#creating the latest release driver url based on the major version of the chrome
**latestDriverReleaseURL=$baseDriverLatestReleaseURL$chromeMajorVersion**
**echo $latestDriverReleaseURL**
#file name of the file that gets downloaded which would contain the full version of the chrome driver to download
**latestDriverVersionFileName="LATEST_RELEASE_"$chromeMajorVersion**
#downloading the file that would contain the full release version compatible with the major release of the chrome browser version
**wget $latestDriverReleaseURL**
#reading the file to get the version of the chrome driver that we should download
**latestFullDriverVersion=$(cat $latestDriverVersionFileName)**
**echo $latestFullDriverVersion**
#creating the final URL by passing the compatible version of the chrome driver that we should download
**finalURL="https://chromedriver.storage.googleapis.com/"$latestFullDriverVersion"/chromedriver_linux64.zip"**
**echo $finalURL**
**wget $finalURL**
I was able to get the compatible version of chrome browser and chrome driver using the above approach when running scheduled job on the databricks environment and it worked like a charm without any issues.
Hope it helps others in one way or other.
Use regex.test()
if all you want is a boolean result:
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
_x000D_
...and you could remove the ()
from your regexp since you've no need for a capture.
Replace the separator with TAB(\t) instead of comma(,). Then open the file in your editor (Notepad etc.), copy the content from there, then paste it in the Excel file.
If you have your CSS in the internal file storage you can use
//Get a reference to your webview
WebView web = (WebView)findViewById(R.id.webby);
// Prepare some html, it is formated with css loaded from the file style.css
String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>"
+ "<body><div class=\"running\">I am a text rendered with INDIGO</div></body></html>";
//get and format the path pointing to the internal storage
String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/";
//load the html with the baseURL, all files relative to the baseURL will be found
web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");
First of all you need to create a surface once and keep it somewhere handy. Example:
var surface = dojox.gfx.createSurface(domNode, widthInPx, heightInPx);
domNode
is usually an unadorned <div>
, which is used as a placeholder for a surface.
You can clear everything on the surface in one go (all existing shape objects will be invalidated, don't use them after that):
surface.clear();
All surface-related functions and methods can be found in the official documentation on dojox.gfx.Surface. Examples of use can be found in dojox/gfx/tests/
.
modinfo
does the trick.
root@nyx:/usr/src# modinfo nvidia|grep version:
version: 331.113
This is covered in the documentation under the section "Static Resources":
The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.
// GOOD
<Image source={require('image!my-icon')} />
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)} />
// GOOD
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
<Image source={icon} />
However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
what about
if(MyType as IMyInterface != null)
?
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Should be:
Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
I'm always running tests against an in-memory DB (HSQLDB or Derby) for these reasons:
The in-memory DB is loaded with fresh data once the tests start and after most tests, I invoke ROLLBACK to keep it stable. ALWAYS keep the data in the test DB stable! If the data changes all the time, you can't test.
The data is loaded from SQL, a template DB or a dump/backup. I prefer dumps if they are in a readable format because I can put them in VCS. If that doesn't work, I use a CSV file or XML. If I have to load enormous amounts of data ... I don't. You never have to load enormous amounts of data :) Not for unit tests. Performance tests are another issue and different rules apply.
Another useful resource:
http://psoug.org/reference/roles.html
BEGIN and END have been well answered by others.
As Gary points out, GO is a batch separator, used by most of the Microsoft supplied client tools, such as isql, sqlcmd, query analyzer and SQL Server Management studio. (At least some of the tools allow the batch separator to be changed. I have never seen a use for changing the batch separator.)
To answer the question of when to use GO, one needs to know when the SQL must be separated into batches.
Some statements must be the first statement of a batch.
select 1
create procedure #Zero as
return 0
On SQL Server 2000 the error is:
Msg 111, Level 15, State 1, Line 3
'CREATE PROCEDURE' must be the first statement in a query batch.
Msg 178, Level 15, State 1, Line 4
A RETURN statement with a return value cannot be used in this context.
On SQL Server 2005 the error is less helpful:
Msg 178, Level 15, State 1, Procedure #Zero, Line 5
A RETURN statement with a return value cannot be used in this context.
So, use GO
to separate statements that have to be the start of a batch from the statements that precede it in a script.
When running a script, many errors will cause execution of the batch to stop, but then the client will simply send the next batch, execution of the script will not stop. I often use this in testing. I will start the script with begin transaction and end with rollback, doing all the testing in the middle:
begin transaction
go
... test code here ...
go
rollback transaction
That way I always return to the starting state, even if an error happened in the test code, the begin and rollback transaction statements being part of a separate batches still happens. If they weren't in separate batches, then a syntax error would keep begin transaction from happening, since a batch is parsed as a unit. And a runtime error would keep the rollback from happening.
Also, if you are doing an install script, and have several batches in one file, an error in one batch will not keep the script from continuing to run, which may leave a mess. (Always backup before installing.)
Related to what Dave Markel pointed out, there are cases when parsing will fail because SQL Server is looking in the data dictionary for objects that are created earlier in the batch, but parsing can happen before any statements are run. Sometimes this is an issue, sometimes not. I can't come up with a good example. But if you ever get an 'X does not exist' error, when it plainly will exist by that statement break into batches.
And a final note. Transaction can span batches. (See above.) Variables do not span batches.
declare @i int
set @i = 0
go
print @i
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@i".
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
I created my own script, because I found many plugins to be quite bloated, and I just wanted it to work the way I wanted. Mine checks to see if each image has a height (native image height). I've combined that with the $(window).load() function to get around the issues of caching.
I've code commented it quite heavily, so it should be interesting to look at, even if you don't use it. It works perfectly for me.
Without further ado, here it is:
I was facing the same issue and solve it by just replacing VARCHAR
with CLOB
.
This link helped me out.
When a thread is executing and you want to execute the main UI thread which is blocked by current thread, then use the below:
current thread:
Dispatcher.CurrentDispatcher.Invoke(MethodName,
new object[] { parameter1, parameter2 }); // if passing 2 parameters to method.
Main UI thread:
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new Action(() => MethodName(parameter)));
Non-recursive DFS using ES6 generators
class Node {
constructor(name, childNodes) {
this.name = name;
this.childNodes = childNodes;
this.visited = false;
}
}
function *dfs(s) {
let stack = [];
stack.push(s);
stackLoop: while (stack.length) {
let u = stack[stack.length - 1]; // peek
if (!u.visited) {
u.visited = true; // grey - visited
yield u;
}
for (let v of u.childNodes) {
if (!v.visited) {
stack.push(v);
continue stackLoop;
}
}
stack.pop(); // black - all reachable descendants were processed
}
}
It deviates from typical non-recursive DFS to easily detect when all reachable descendants of given node were processed and to maintain the current path in the list/stack.
It is actually executing the command, changing the directory to some_directory
, however, this is performed in a sub-process shell, and affects neither make nor the shell you're working from.
If you're looking to perform more tasks within some_directory
, you need to add a semi-colon and append the other commands as well. Note that you cannot use newlines as they are interpreted by make as the end of the rule, so any newlines you use for clarity needs to be escaped by a backslash.
For example:
all:
cd some_dir; echo "I'm in some_dir"; \
gcc -Wall -o myTest myTest.c
Note also that the semicolon is necessary between every command even though you add a backslash and a newline. This is due to the fact that the entire string is parsed as a single line by the shell. As noted in the comments, you should use '&&' to join commands, which mean they only get executed if the preceding command was successful.
all:
cd some_dir && echo "I'm in some_dir" && \
gcc -Wall -o myTest myTest.c
This is especially crucial when doing destructive work, such as clean-up, as you'll otherwise destroy the wrong stuff, should the cd
fail for whatever reason.
A common usage though is to call make in the sub directory, which you might want to look into. There's a command line option for this so you don't have to call cd
yourself, so your rule would look like this
all:
$(MAKE) -C some_dir all
which will change into some_dir
and execute the Makefile
in there with the target "all". As a best practice, use $(MAKE)
instead of calling make
directly, as it'll take care to call the right make instance (if you, for example, use a special make version for your build environment), as well as provide slightly different behavior when running using certain switches, such as -t
.
For the record, make always echos the command it executes (unless explicitly suppressed), even if it has no output, which is what you're seeing.
You need to use the Disposable Pattern like this:
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose any managed objects
// ...
}
// Now disposed of any unmanaged objects
// ...
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Destructor
~YourClassName()
{
Dispose(false);
}
By default, Xcode sets the bundle identifier to the bundle/company identifier that you set during project creation + project name.
This is similar to what you see in the Project > Summary screen.
But you can change this in the Project > Info screen. (This is the Info.plist.)
To remove a specific variable from the session use:
session_unregister('variableName');
(see documentation) or
unset($_SESSION['variableName']);
NOTE:
session_unregister()
has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"
Use read -p
:
# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user
If you like to confirm:
read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
You should also quote your variables to prevent pathname expansion and word splitting with spaces:
# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"
When you use an async function like
async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
}
it returns a promise and useEffect
doesn't expect the callback function to return Promise, rather it expects that nothing is returned or a function is returned.
As a workaround for the warning you can use a self invoking async function.
useEffect(() => {
(async function() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
})();
}, []);
or to make it more cleaner you could define a function and then call it
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
};
fetchData();
}, []);
the second solution will make it easier to read and will help you write code to cancel previous requests if a new one is fired or save the latest request response in state
Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.
More Info
This solution is not perfect, but it gives some benefits:
First of all, here's working example, so you can test it before going further.
Installation:
Data > Validation
Prepare Data
Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:
Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.
First simple Data Validation (DV)
Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A)
On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.
Script
Paste this code into script editor:
function onEdit(event) _x000D_
{_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data1'; // name of sheet with data_x000D_
var NumOfLevels = 4; // number of levels of data validation_x000D_
var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,2]; // offsets for levels_x000D_
// ^ means offset column #4 on one position right._x000D_
_x000D_
// =====================================================================================_x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data2'; // name of sheet with data_x000D_
var NumOfLevels = 7; // number of levels of data validation_x000D_
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,1,1,1,1]; // offsets for levels_x000D_
// ===================================================================================== _x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets) _x000D_
{_x000D_
//--------------------------------------------------------------------------------------_x000D_
// The event handler, adds data validation for the input parameters_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
// =================================== key variables =================================_x000D_
//_x000D_
// ss sheet we change (TargetSheet)_x000D_
// br range to change_x000D_
// scol number of column to edit_x000D_
// srow number of row to edit _x000D_
// CurrentLevel level of drop-down, which we change_x000D_
// HeadLevel main level_x000D_
// r current cell, which was changed by user_x000D_
// X number of levels could be checked on the right_x000D_
//_x000D_
// ls Data sheet (LogSheet)_x000D_
//_x000D_
// ======================================================================================_x000D_
_x000D_
// Checks_x000D_
var ts = event.source.getActiveSheet();_x000D_
var sname = ts.getName(); _x000D_
if (sname !== TargetSheet) { return -1; } // not main sheet_x000D_
// Test if range fits_x000D_
var br = event.range;_x000D_
var scol = br.getColumn(); // the column number in which the change is made_x000D_
var srow = br.getRow() // line number in which the change is made_x000D_
var ColNum = br.getWidth();_x000D_
_x000D_
if ((scol + ColNum - 1) < lcol) { return -2; } // columns... _x000D_
if (srow < lrow) { return -3; } // rows_x000D_
// Test range is in levels_x000D_
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels _x000D_
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);_x000D_
if(CurrentLevel === 1) { return -4; } // out of data validations_x000D_
if(CurrentLevel > NumOfLevels) { return -5; } // last level _x000D_
_x000D_
_x000D_
/*_x000D_
ts - sheet with validation, sname = name of sheet_x000D_
_x000D_
NumOfLevels = 4 _x000D_
offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column_x000D_
columnsLevels = [4,5,6,8] - Columns of validation_x000D_
_x000D_
Columns 7 is skipped_x000D_
|_x000D_
1 2 3 4 5 6 7 8 9 _x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
1 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
2 | | | | v | V | ? | x | ? | | lrow = 2 - number of row where validation starts_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
3 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
4 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
| | | | |_x000D_
| | | | Currentlevel = 3 - the number of level to change_x000D_
| | | |_x000D_
| | | br - cell, user changes: scol - column, srow - row,_x000D_
| | ColNum = 1 - width _x000D_
|__|________ _.....____|_x000D_
| v_x000D_
| Drop-down lists _x000D_
|_x000D_
| lcol = 4 - number of column where validation starts_x000D_
*/_x000D_
// Constants_x000D_
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals_x000D_
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet _x000D_
var RowNum = br.getHeight();_x000D_
/* Adjust the range 'br' _x000D_
??? !_x000D_
xxx x_x000D_
xxx x _x000D_
xxx => x_x000D_
xxx x_x000D_
xxx x_x000D_
*/ _x000D_
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum); _x000D_
// Levels_x000D_
var HeadLevel = CurrentLevel - 1; // main level_x000D_
var X = NumOfLevels - CurrentLevel + 1; // number of levels left _x000D_
// determine columns on the sheet "Data"_x000D_
var KudaCol = NumOfLevels + 2;_x000D_
var KudaNado = ls.getRange(1, KudaCol); // 1 place for a formula_x000D_
var lastRow = ls.getLastRow();_x000D_
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula_x000D_
_x000D_
// ============================================================================= > loop >_x000D_
var CurrLevelBase = CurrentLevel; // remember the first current level_x000D_
_x000D_
_x000D_
_x000D_
for (var j = 1; j <= RowNum; j++) // [01] loop rows start_x000D_
{ _x000D_
// refresh first val _x000D_
var currentRow = br.getCell(j, 1).getRow(); _x000D_
loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} // [01] loop rows end_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getColumnsOffset_(offsets, lefColumn)_x000D_
{_x000D_
// Columns for all levels_x000D_
var columnsLevels = [];_x000D_
var totalOffset = 0; _x000D_
for (var i = 0, l = offsets.length; i < l; i++)_x000D_
{ _x000D_
totalOffset += offsets[i];_x000D_
columnsLevels.push(totalOffset + lefColumn - 1);_x000D_
} _x000D_
_x000D_
return columnsLevels;_x000D_
_x000D_
}_x000D_
_x000D_
function test_getCurrentLevel()_x000D_
{_x000D_
var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');_x000D_
var scol = 1;_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/_x000D_
Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxx| |xxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxxxxxxxx| _x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxx| |xxxxx| _x000D_
levels 1 2 3_x000D_
level 3_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 4 (error)_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels _x000D_
level 1 (error) _x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1 _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getCurrentLevel_(ColNum, br, scol, columnsLevels)_x000D_
{_x000D_
var colPlus = 2; // const_x000D_
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }_x000D_
var CurrentLevel = -1;_x000D_
var level = 0;_x000D_
var column = 0;_x000D_
for (var i = 0; i < ColNum; i++ )_x000D_
{_x000D_
column = br.offset(0, i).getColumn();_x000D_
level = columnsLevels.indexOf(column) + colPlus;_x000D_
if (level > CurrentLevel) { CurrentLevel = level; }_x000D_
}_x000D_
return CurrentLevel;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
for (var k = 1; k <= X; k++)_x000D_
{ _x000D_
HeadLevel = HeadLevel + k - 1; _x000D_
CurrentLevel = CurrLevelBase + k - 1;_x000D_
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);_x000D_
var SearchText = r.getValue(); // searched text _x000D_
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} _x000D_
}_x000D_
_x000D_
_x000D_
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
_x000D_
_x000D_
// if nothing is chosen!_x000D_
if (SearchText === '') // condition value =''_x000D_
{_x000D_
// kill extra data validation if there were _x000D_
// columns on the right_x000D_
if (CurrentLevel <= NumOfLevels) _x000D_
{_x000D_
for (var f = 0; f < X; f++) _x000D_
{_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]); _x000D_
// clean & get rid of validation_x000D_
cell.clear({contentsOnly: true}); _x000D_
cell.clear({validationsOnly: true});_x000D_
// exit columns loop _x000D_
}_x000D_
}_x000D_
return 0; // end loop this row _x000D_
}_x000D_
_x000D_
_x000D_
// formula for values_x000D_
var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts); _x000D_
KudaNado.setFormula(formula);_x000D_
_x000D_
_x000D_
// get response_x000D_
var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);_x000D_
var Variants = Response.length;_x000D_
_x000D_
_x000D_
// build data validation rule_x000D_
if (Variants === 0.0) // empty is found_x000D_
{_x000D_
return;_x000D_
} _x000D_
if(Variants >= 1.0) // if some variants were found_x000D_
{_x000D_
_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);_x000D_
var rule = SpreadsheetApp_x000D_
.newDataValidation()_x000D_
.requireValueInList(Response, true)_x000D_
.setAllowInvalid(false)_x000D_
.build();_x000D_
// set validation rule_x000D_
cell.setDataValidation(rule);_x000D_
} _x000D_
if (Variants === 1.0) // // set the only value_x000D_
{ _x000D_
cell.setValue(Response[0]);_x000D_
SearchText = null;_x000D_
Response = null;_x000D_
return X; // continue doing DV_x000D_
} // the only value_x000D_
_x000D_
return 0; // end DV in this row_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)_x000D_
{_x000D_
_x000D_
var checkVals = [];_x000D_
var Offs = CurrentLevel - 2;_x000D_
var values = [];_x000D_
// get values and display values for a formula_x000D_
for (var s = 0; s <= Offs; s++)_x000D_
{_x000D_
var checkR = ts.getRange(currentRow, columnsLevels[s]);_x000D_
values.push(checkR.getValue());_x000D_
} _x000D_
_x000D_
var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."_x000D_
var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84_x000D_
_x000D_
var mathOpPlusVal = ''; _x000D_
var value = '';_x000D_
_x000D_
// loop levels for multiple conditions _x000D_
for (var i = 0; i < CurrentLevel - 1; i++) { _x000D_
formula += FormulaSplitter; // =unique(filter(A2:A84;_x000D_
LookCol = colName(i);_x000D_
_x000D_
value = values[i];_x000D_
_x000D_
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"_x000D_
_x000D_
if ( Array.isArray(mathOpPlusVal) )_x000D_
{_x000D_
formula += mathOpPlusVal[0];_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84_x000D_
formula += mathOpPlusVal[1];_x000D_
}_x000D_
else_x000D_
{_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84_x000D_
formula += mathOpPlusVal;_x000D_
}_x000D_
_x000D_
_x000D_
} _x000D_
_x000D_
formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))_x000D_
_x000D_
return formula;_x000D_
}_x000D_
_x000D_
_x000D_
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)_x000D_
{_x000D_
var result = '';_x000D_
var splinter = ''; _x000D_
_x000D_
var type = typeof value;_x000D_
_x000D_
_x000D_
// strings_x000D_
if (type === 'string') return '="' + value + '"';_x000D_
// date_x000D_
if(value instanceof Date)_x000D_
{_x000D_
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+' _x000D_
+ 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)']; _x000D_
} _x000D_
// numbers_x000D_
if (type === 'number')_x000D_
{_x000D_
if (ReplaceCommas)_x000D_
{_x000D_
return '+0=' + value.toString().replace('.', ','); _x000D_
}_x000D_
else_x000D_
{_x000D_
return '+0=' + value;_x000D_
}_x000D_
}_x000D_
// booleans_x000D_
if (type === 'boolean')_x000D_
{_x000D_
return '=' + value;_x000D_
} _x000D_
// other_x000D_
return '=' + value;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getResponse_(allRange, l, ReplaceCommas)_x000D_
{_x000D_
var data = allRange.getValues();_x000D_
var data_ = allRange.getDisplayValues();_x000D_
_x000D_
var response = [];_x000D_
var val = '';_x000D_
for (var i = 0; i < l; i++)_x000D_
{_x000D_
val = data[i][0];_x000D_
if (val !== '') _x000D_
{_x000D_
var type = typeof val;_x000D_
if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);_x000D_
if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')_x000D_
response.push(val); _x000D_
}_x000D_
}_x000D_
_x000D_
return response; _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function colName(n) {_x000D_
var ordA = 'a'.charCodeAt(0);_x000D_
var ordZ = 'z'.charCodeAt(0);_x000D_
_x000D_
var len = ordZ - ordA + 1;_x000D_
_x000D_
var s = "";_x000D_
while(n >= 0) {_x000D_
s = String.fromCharCode(n % len + ordA) + s;_x000D_
n = Math.floor(n / len) - 1;_x000D_
}_x000D_
return s; _x000D_
}_x000D_
_x000D_
_x000D_
function getDecimalMarkIsCommaLocals() {_x000D_
_x000D_
_x000D_
// list of Locals Decimal mark = comma_x000D_
var LANGUAGE_BY_LOCALE = {_x000D_
af_NA: "Afrikaans (Namibia)",_x000D_
af_ZA: "Afrikaans (South Africa)",_x000D_
af: "Afrikaans",_x000D_
sq_AL: "Albanian (Albania)",_x000D_
sq: "Albanian",_x000D_
ar_DZ: "Arabic (Algeria)",_x000D_
ar_BH: "Arabic (Bahrain)",_x000D_
ar_EG: "Arabic (Egypt)",_x000D_
ar_IQ: "Arabic (Iraq)",_x000D_
ar_JO: "Arabic (Jordan)",_x000D_
ar_KW: "Arabic (Kuwait)",_x000D_
ar_LB: "Arabic (Lebanon)",_x000D_
ar_LY: "Arabic (Libya)",_x000D_
ar_MA: "Arabic (Morocco)",_x000D_
ar_OM: "Arabic (Oman)",_x000D_
ar_QA: "Arabic (Qatar)",_x000D_
ar_SA: "Arabic (Saudi Arabia)",_x000D_
ar_SD: "Arabic (Sudan)",_x000D_
ar_SY: "Arabic (Syria)",_x000D_
ar_TN: "Arabic (Tunisia)",_x000D_
ar_AE: "Arabic (United Arab Emirates)",_x000D_
ar_YE: "Arabic (Yemen)",_x000D_
ar: "Arabic",_x000D_
hy_AM: "Armenian (Armenia)",_x000D_
hy: "Armenian",_x000D_
eu_ES: "Basque (Spain)",_x000D_
eu: "Basque",_x000D_
be_BY: "Belarusian (Belarus)",_x000D_
be: "Belarusian",_x000D_
bg_BG: "Bulgarian (Bulgaria)",_x000D_
bg: "Bulgarian",_x000D_
ca_ES: "Catalan (Spain)",_x000D_
ca: "Catalan",_x000D_
tzm_Latn: "Central Morocco Tamazight (Latin)",_x000D_
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",_x000D_
tzm: "Central Morocco Tamazight",_x000D_
da_DK: "Danish (Denmark)",_x000D_
da: "Danish",_x000D_
nl_BE: "Dutch (Belgium)",_x000D_
nl_NL: "Dutch (Netherlands)",_x000D_
nl: "Dutch",_x000D_
et_EE: "Estonian (Estonia)",_x000D_
et: "Estonian",_x000D_
fi_FI: "Finnish (Finland)",_x000D_
fi: "Finnish",_x000D_
fr_BE: "French (Belgium)",_x000D_
fr_BJ: "French (Benin)",_x000D_
fr_BF: "French (Burkina Faso)",_x000D_
fr_BI: "French (Burundi)",_x000D_
fr_CM: "French (Cameroon)",_x000D_
fr_CA: "French (Canada)",_x000D_
fr_CF: "French (Central African Republic)",_x000D_
fr_TD: "French (Chad)",_x000D_
fr_KM: "French (Comoros)",_x000D_
fr_CG: "French (Congo - Brazzaville)",_x000D_
fr_CD: "French (Congo - Kinshasa)",_x000D_
fr_CI: "French (Côte d’Ivoire)",_x000D_
fr_DJ: "French (Djibouti)",_x000D_
fr_GQ: "French (Equatorial Guinea)",_x000D_
fr_FR: "French (France)",_x000D_
fr_GA: "French (Gabon)",_x000D_
fr_GP: "French (Guadeloupe)",_x000D_
fr_GN: "French (Guinea)",_x000D_
fr_LU: "French (Luxembourg)",_x000D_
fr_MG: "French (Madagascar)",_x000D_
fr_ML: "French (Mali)",_x000D_
fr_MQ: "French (Martinique)",_x000D_
fr_MC: "French (Monaco)",_x000D_
fr_NE: "French (Niger)",_x000D_
fr_RW: "French (Rwanda)",_x000D_
fr_RE: "French (Réunion)",_x000D_
fr_BL: "French (Saint Barthélemy)",_x000D_
fr_MF: "French (Saint Martin)",_x000D_
fr_SN: "French (Senegal)",_x000D_
fr_CH: "French (Switzerland)",_x000D_
fr_TG: "French (Togo)",_x000D_
fr: "French",_x000D_
gl_ES: "Galician (Spain)",_x000D_
gl: "Galician",_x000D_
ka_GE: "Georgian (Georgia)",_x000D_
ka: "Georgian",_x000D_
de_AT: "German (Austria)",_x000D_
de_BE: "German (Belgium)",_x000D_
de_DE: "German (Germany)",_x000D_
de_LI: "German (Liechtenstein)",_x000D_
de_LU: "German (Luxembourg)",_x000D_
de_CH: "German (Switzerland)",_x000D_
de: "German",_x000D_
el_CY: "Greek (Cyprus)",_x000D_
el_GR: "Greek (Greece)",_x000D_
el: "Greek",_x000D_
hu_HU: "Hungarian (Hungary)",_x000D_
hu: "Hungarian",_x000D_
is_IS: "Icelandic (Iceland)",_x000D_
is: "Icelandic",_x000D_
id_ID: "Indonesian (Indonesia)",_x000D_
id: "Indonesian",_x000D_
it_IT: "Italian (Italy)",_x000D_
it_CH: "Italian (Switzerland)",_x000D_
it: "Italian",_x000D_
kab_DZ: "Kabyle (Algeria)",_x000D_
kab: "Kabyle",_x000D_
kl_GL: "Kalaallisut (Greenland)",_x000D_
kl: "Kalaallisut",_x000D_
lv_LV: "Latvian (Latvia)",_x000D_
lv: "Latvian",_x000D_
lt_LT: "Lithuanian (Lithuania)",_x000D_
lt: "Lithuanian",_x000D_
mk_MK: "Macedonian (Macedonia)",_x000D_
mk: "Macedonian",_x000D_
naq_NA: "Nama (Namibia)",_x000D_
naq: "Nama",_x000D_
pl_PL: "Polish (Poland)",_x000D_
pl: "Polish",_x000D_
pt_BR: "Portuguese (Brazil)",_x000D_
pt_GW: "Portuguese (Guinea-Bissau)",_x000D_
pt_MZ: "Portuguese (Mozambique)",_x000D_
pt_PT: "Portuguese (Portugal)",_x000D_
pt: "Portuguese",_x000D_
ro_MD: "Romanian (Moldova)",_x000D_
ro_RO: "Romanian (Romania)",_x000D_
ro: "Romanian",_x000D_
ru_MD: "Russian (Moldova)",_x000D_
ru_RU: "Russian (Russia)",_x000D_
ru_UA: "Russian (Ukraine)",_x000D_
ru: "Russian",_x000D_
seh_MZ: "Sena (Mozambique)",_x000D_
seh: "Sena",_x000D_
sk_SK: "Slovak (Slovakia)",_x000D_
sk: "Slovak",_x000D_
sl_SI: "Slovenian (Slovenia)",_x000D_
sl: "Slovenian",_x000D_
es_AR: "Spanish (Argentina)",_x000D_
es_BO: "Spanish (Bolivia)",_x000D_
es_CL: "Spanish (Chile)",_x000D_
es_CO: "Spanish (Colombia)",_x000D_
es_CR: "Spanish (Costa Rica)",_x000D_
es_DO: "Spanish (Dominican Republic)",_x000D_
es_EC: "Spanish (Ecuador)",_x000D_
es_SV: "Spanish (El Salvador)",_x000D_
es_GQ: "Spanish (Equatorial Guinea)",_x000D_
es_GT: "Spanish (Guatemala)",_x000D_
es_HN: "Spanish (Honduras)",_x000D_
es_419: "Spanish (Latin America)",_x000D_
es_MX: "Spanish (Mexico)",_x000D_
es_NI: "Spanish (Nicaragua)",_x000D_
es_PA: "Spanish (Panama)",_x000D_
es_PY: "Spanish (Paraguay)",_x000D_
es_PE: "Spanish (Peru)",_x000D_
es_PR: "Spanish (Puerto Rico)",_x000D_
es_ES: "Spanish (Spain)",_x000D_
es_US: "Spanish (United States)",_x000D_
es_UY: "Spanish (Uruguay)",_x000D_
es_VE: "Spanish (Venezuela)",_x000D_
es: "Spanish",_x000D_
sv_FI: "Swedish (Finland)",_x000D_
sv_SE: "Swedish (Sweden)",_x000D_
sv: "Swedish",_x000D_
tr_TR: "Turkish (Turkey)",_x000D_
tr: "Turkish",_x000D_
uk_UA: "Ukrainian (Ukraine)",_x000D_
uk: "Ukrainian",_x000D_
vi_VN: "Vietnamese (Vietnam)",_x000D_
vi: "Vietnamese"_x000D_
}_x000D_
_x000D_
_x000D_
var SS = SpreadsheetApp.getActiveSpreadsheet();_x000D_
var LocalS = SS.getSpreadsheetLocale();_x000D_
_x000D_
_x000D_
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {_x000D_
return false;_x000D_
_x000D_
}_x000D_
//Logger.log(true);_x000D_
return true;_x000D_
}_x000D_
_x000D_
/*_x000D_
function ReplaceDotsToCommas(dataIn) {_x000D_
var dataOut = dataIn.map(function(num) {_x000D_
if (isNaN(num)) {_x000D_
return num;_x000D_
} _x000D_
num = num.toString();_x000D_
return num.replace(".", ",");_x000D_
});_x000D_
return dataOut;_x000D_
}_x000D_
*/
_x000D_
Here's set of variables that are to be changed, you'll find them in script:
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.
If you need to order your code into namespaces, just use the keyword namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use
. If in file2 you put
use foo\bar as mypath;
you need to use mypath
instead of bar
anywhere in the file:
$obj = new mypath\myObj();
Using use foo\bar;
is equal to use foo\bar as bar;
.
ALTER TABLE `subscriber_surname` ADD IF NOT EXISTS `#__comm_subscribers`.`subscriber_surname`;
ALTER TABLE `#__comm_subscribers` MODIFY `subscriber_surname` varchar(64) NOT NULL default '';
on Mac:
select all matches: Command + Shift + L
but if you just want to select another match up coming next: Command + D
you need to add Content-Disposition header, smth like this (although I used mod-python here, but principle should be the same):
request.headers_out['Content-Disposition'] = 'attachment; filename=%s' % myfname
Here is another one variant to save .toFixed([digits]) functional without rounding float variable:
Number.prototype.toRealFixed = function(digits) {
return Math.floor(this.valueOf() * Math.pow(10, digits)) / Math.pow(10, digits);
};
And calling:
var float_var = 0.02209062;
float_var.toRealFixed();
You installed the Java Runtime Environment (JRE) only, which does not contain javac
. For javac
, you have to install the OpenJDK Development Environment. You can install java-devel
or java-1.6.0-openjdk-devel
, which both include javac
.
By the way: you can find out which package provides javac
with a yum
search, e.g.
su -c 'yum provides javac'
on more recent releases of CentOS e.g. 6 the command changes to
su -c 'yum provides */javac'
Another note: using yum
and openjdk
is only one possibility to install the JDK. Many people prefer Sun/Oracle's "original" SDK. See How to install Java SDK on CentOS? and links for alternatives.
also, to get the right arrow, right click and "Add as Library".
In case you're experiencing this issue with an application whose source you cannot modify consider invoking it with the environment variable NODE_DEBUG
set to child_process
, e.g. NODE_DEBUG=child_process yarn test
. This will provide you with information which command lines have been invoked in which directory and usually the last detail is the reason for the failure.
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
Did you set the proper settings in pg_hba.conf?
See https://help.ubuntu.com/stable/serverguide/postgresql.html how to do it.
keep the delimiter in single quotes it will work.
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
This will work
extern template
is only needed if the template declaration is complete
This was hinted at in other answers, but I don't think enough emphasis was given to it.
What this means is that in the OPs examples, the extern template
has no effect because the template definitions on the headers were incomplete:
void f();
: just declaration, no bodyclass foo
: declares method f()
but has no definitionSo I would recommend just removing the extern template
definition in that particular case: you only need to add them if the classes are completely defined.
For example:
TemplHeader.h
template<typename T>
void f();
TemplCpp.cpp
template<typename T>
void f(){}
// Explicit instantiation for char.
template void f<char>();
Main.cpp
#include "TemplHeader.h"
// Commented out from OP code, has no effect.
// extern template void f<T>(); //is this correct?
int main() {
f<char>();
return 0;
}
compile and view symbols with nm
:
g++ -std=c++11 -Wall -Wextra -pedantic -c -o TemplCpp.o TemplCpp.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -c -o Main.o Main.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -o Main.out Main.o TemplCpp.o
echo TemplCpp.o
nm -C TemplCpp.o | grep f
echo Main.o
nm -C Main.o | grep f
output:
TemplCpp.o
0000000000000000 W void f<char>()
Main.o
U void f<char>()
and then from man nm
we see that U
means undefined, so the definition did stay only on TemplCpp
as desired.
All this boils down to the tradeoff of complete header declarations:
extern template
on every includer, which programmers will likely forget to doFurther examples of those are shown at: Explicit template instantiation - when is it used?
Since compilation time is so critical in large projects, I would highly recommend incomplete template declarations, unless external parties absolutely need to reuse your code with their own complex custom classes.
And in that case, I would first try to use polymorphism to avoid the build time problem, and only use templates if noticeable performance gains can be made.
Tested in Ubuntu 18.04.
Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.
Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).
Django is server-side. It means, say a client goes to a URL, you have a function inside views
that renders what he sees and returns a response in HTML. Let's break it up into examples:
views.py:
def hello(request):
return HttpResponse('Hello World!')
def home(request):
return render_to_response('index.html', {'variable': 'world'})
index.html:
<h1>Hello {{ variable }}, welcome to my awesome site</h1>
urls.py:
url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),
That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello
means a request to the hello()
function, going to 127.0.0.1:8000/home
will return the index.html
and replace all the variables as asked (you probably know all this by now).
Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.
For example, an AJAX call to 127.0.0.1:8000/hello
will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you'd like. Let's look at a simple use case:
$.ajax({
url: '127.0.0.1:8000/hello',
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});
The general process is this:
127.0.0.1:8000/hello
as if you opened a new tab and did it yourself.Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an AJAX call to home? Same thing, you'll get an alert stating <h1>Hello world, welcome to my awesome site</h1>
.
In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:
console.log
things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.csrf_token
. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token
. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.
Using fetch for example like below:
fetch(<"yoururl">, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + <your access token if need>
},
})
.then((response) => response.blob())
.then((blob) => {
// 2. Create blob link to download
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `sample.xlsx`);
// 3. Append to html page
document.body.appendChild(link);
// 4. Force download
link.click();
// 5. Clean up and remove the link
link.parentNode.removeChild(link);
})
You can paste in on Chrome console to test. the file with download with 'sample.xlsx' Hope it can help!
This worked:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
Firebug Output:
<select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You could also use .prependTo
if you wanted to reverse the order:
?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????
value="<?php echo htmlspecialchars($name); ?>"
The problem here is that you have defined ID as a field in your data file when what you want is to just use an expression without any data from the data file. You can fix this by defining ID as an expression (or a sequence in this case)
ID EXPRESSION "ID_SEQ.nextval"
or
ID SEQUENCE(count)
See: http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_field_list.htm#i1008234 for all options
Sorry, it is a reponse to an old thread, but might still be usefull.
In addition to above reponses, This genrally happens when two columns with same name, even from different tables are included in the same query. for example if we joining two tables city and state where tables have column name e.g. city.name and state.name. when such a query is added to the dataset, ssrs removes the table name or the table alias and only keeps the name, whih eventually appears twice in the query and errors as duplicate key. The best way to avoid it is to use alias such as calling the column names city.name as c_name state.name as s_name. This will resolve the issue.
A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.
If you want to update e.g. only the width you can do that with the following line in Kotlin.
tv.updateLayoutParams { width = WRAP_CONTENT }
I think this is what you're looking for (Laravel 4, see http://laravel.com/docs/eloquent#querying-relations)
$games = Game::whereHas('video', function($q)
{
$q->where('available','=', 1);
})->get();
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
In my case I wanted to check if a complete URL is encoded, so I already knew that the URL must contain the string https://
, and what I did was to check if the string had the encoded version of https://
in it (https%3A%2F%2F
) and if it didn't, then I knew it was not encoded:
//make sure $completeUrl is encoded
if (strpos($completeUrl, urlencode('https://')) === false) {
// not encoded, need to encode it
$completeUrl = urlencode($completeUrl);
}
in theory this solution can be used with any string other than complete URLs, as long as you know part of the string (https://
in this example) will always exists in what you are trying to check.
if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.
-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.
I think that second thing is better because you give to java the automatic memory management.
Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
</Grid.Background>
<...>
</Grid>
On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.
On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.
A well written blog post: http://www.johnpapa.net/angular-growth-structure/
Example App: https://github.com/angular-app/angular-app
The simplest one got to be:
def html = "http://google.com".toURL().text
Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:
myLong = CLng(rs!AutoNumberField)
returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.
myLong = DLookup("AutoNumberField","TableName","SomeCriteria")
will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.
Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:
$(".phone").keyup(function () {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.
<a [routerLink]="[{ outlets: { list:['streams'], details:['parties'] } }]">Link</a>
<div id="list">
<router-outlet name="list"></router-outlet>
</div>
<div id="details">
<router-outlet name="details"></router-outlet>
</div>
`
{
path: 'admin',
component: AdminLayoutComponent,
children:[
{
path: '',
component: AdminStreamsComponent,
outlet:'list'
},
{
path: 'stream/:id',
component: AdminStreamComponent,
outlet:'details'
}
]
}
As far as I know, there is no standard way to achieve this with only CSS, although I think there should be. Mozilla browsers used to support fixed headers with a scrolling body, but they've removed it in the last few years.
After researching this a bit, including finding this posting, a friend just developed this solution for me; it uses Javascript but no canned libraries, and the only requirement for the HTML markup is that the table have an id name. Then, at window.onload, to call one Javascript function for each table giving the id, height, and width. If Javascript is disabled at the browser, the whole table is displayed according to its original markup. If Javascript is enabled, the table is fit into the specified height and width, and tbody scrolls, and if thead and tfoot exist, they are fixed at top and bottom.
The code snippet below works on both Eclipse and the Python shell:
import numpy as np
import matplotlib.pyplot as plt
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Just print x and y for fun
print x
print y
# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)
# Without the line below, the figure won't show
plt.show()
That's because you want @selector(lowercaseString)
, not @selector(lowercaseString:)
. There's a subtle difference: the second one implies a parameter (note the colon at the end), but - [NSString lowercaseString]
does not take a parameter.
For current ActiveRecord (4.2.4+) there is a method to_hash
on the Result
object that returns an array of hashes. You can then map over it and convert to symbolized hashes:
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
{:id => 2, :title => "title_2", :body => "body_2"},
...
]
Use display: none
instead. Besides, this is probably what you need, because this also truncates the page by removing the space the table occupies, whereas visibility: hidden
leaves the white space left by the table.
The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:
FileSystemWatcher watcher;
private void watch()
{
watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
//Copies file to another directory.
}
Try
$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));
working example here
I used jruby-1.7.4 to compile my ruby code.
require 'roman-numerals.rb'
is the code which threw the below error.
LoadError: no such file to load -- roman-numerals
require at org/jruby/RubyKernel.java:1054
require at /Users/amanoharan/.rvm/rubies/jruby-1.7.4/lib/ruby/shared/rubygems/custom_require.rb:36
(root) at /Users/amanoharan/Documents/Aptana Studio 3 Workspace/RubyApplication/RubyApplication1/Ruby2.rb:2
I removed rb from require and gave
require 'roman-numerals'
It worked fine.
For a complete removal of Xcode 10 delete the following:
/Applications/Xcode.app
~/Library/Caches/com.apple.dt.Xcode
~/Library/Developer
~/Library/MobileDevice
~/Library/Preferences/com.apple.dt.Xcode.plist
/Library/Preferences/com.apple.dt.Xcode.plist
/System/Library/Receipts/com.apple.pkg.XcodeExtensionSupport.bom
/System/Library/Receipts/com.apple.pkg.XcodeExtensionSupport.plist
/System/Library/Receipts/com.apple.pkg.XcodeSystemResources.bom
/System/Library/Receipts/com.apple.pkg.XcodeSystemResources.plist
/private/var/db/receipts/com.apple.pkg.Xcode.bom
But instead of 11, open up /private/var/
in the Finder and search for "Xcode" to see all the 'dna' left behind... and selectively clean that out too. I would post the pathnames but they will include randomized folder names which will not be the same from my Mac to yours.
but if you don't want to lose all of your customizations, consider saving these files or folders before deleting anything:
~/Library/Developer/Xcode/UserData/CodeSnippets
~/Library/Developer/Xcode/UserData/FontAndColorThemes
~/Library/Developer/Xcode/UserData/KeyBindings
~/Library/Developer/Xcode/Templates
~/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/MobileDevice/Provisioning Profiles
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
If you're able to use ES6 and Babel, you can use this new feature:
{
[yourKeyVariable]: someValueArray,
}
The best answer is to add a Resources/.gitignore file under Resources containing:
# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo
If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:
# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo
You will need to edit that pattern if you add directories deeper than specified.
i didn't solve the problem, sadly. but managed to make to codes work (almost all of my codes have this probelm btw) the local issuer certificate problem happens under python3.7 so i changed back to python2.7 QAQ and all that needed to change including "from urllib2 import urlopen" instead of "from urllib.request import urlopen" so sad...
Place mysql-connector-java-5.1.6-bin.jar to the \Apache Tomcat 6.0.18\lib folder. Your problem will be solved.
I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.
First, if I'm understanding your question, you want to store your object into a String and then later to be able to read it again and re-create the Object.
Personally, when I need to do that I use ObjectOutputStream. However, there is a mandatory condition. The object you want to convert to a String and then back to an Object must be a Serializable object, and also all its attributes.
Let's Consider ReadWriteObject
, the object to manipulate and ReadWriteTest
the manipulator.
Here is how I would do it:
public class ReadWriteObject implements Serializable {
/** Serial Version UID */
private static final long serialVersionUID = 8008750006656191706L;
private int age;
private String firstName;
private String lastName;
/**
* @param age
* @param firstName
* @param lastName
*/
public ReadWriteObject(int age, String firstName, String lastName) {
super();
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ReadWriteObject [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
public class ReadWriteTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Create Object to write and then to read
// This object must be Serializable, and all its subobjects as well
ReadWriteObject inputObject = new ReadWriteObject(18, "John", "Doe");
// Read Write Object test
// Write Object into a Byte Array
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(inputObject);
byte[] rawData = baos.toByteArray();
String rawString = new String(rawData);
System.out.println(rawString);
// Read Object from the Byte Array
byte[] byteArrayFromString = rawString.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayFromString);
ObjectInputStream ois = new ObjectInputStream(bais);
Object outputObject = ois.readObject();
System.out.println(outputObject);
}
}
The Standard Output is similar to that (actually, I can't copy/paste it) :
¬í ?sr ?*com.ajoumady.stackoverflow.ReadWriteObjecto$˲é¦LÚ ?I ?ageL ?firstNamet ?Ljava/lang/String;L ?lastNameq ~ ?xp ?t ?John ?Doe
ReadWriteObject [age=18, firstName=John, lastName=Doe]
Use Select-Object
(whose alias is select
) with the -Unique
switch; e.g.:
$a = @(1,2,3,4,5,5,6,7,8,9,0,0)
$a = $a | select -Unique
Technically this does not answer the question, but I would recommend using the Room database instead of any global variable. https://developer.android.com/topic/libraries/architecture/room.html Even if you are 'only' needing to store a global variable and it's no big deal and what not, but using the Room database is the most elegant, native and well supported way of keeping values around the life cycle of the activity. It will help to prevent many issues, especially integrity of data. I understand that database and global variable are different but please use Room for the sake of code maintenance, app stability and data integrity.
Also make sure to update your Oracle VM Virtual Box. I tried everything but later realized that the issue was due to the use of older version of Virtual Box.
You can use the phpmyadmin setup page (./phpmyadmin/setup) to generate a new config file (config.inc.php
) for you. This file is found at the root of the phpMyAdmin directory.
Just create the config folder as prompted in setup page, add your servers, then click the 'Save' button. This will create a new config file in the config folder you just created.
You now have only to move the config.inc.php
file to the main phpMyAdmin folder, or just copy the lines concerning the servers if you got some old configuration done already you'd like to keep.
Don't forget to delete the config folder afterwards.
Well, I have tried something I hope it helps ..
They changed the schema a little bit ..
Use the following :
1- Change the AccessDataSource to SQLDataSource in the toolbox.
2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)
3- Next -> Next -> Test Query -> Finish.
Worked for me.
In case if someone is using Gradle for the build then fix will be by adding the following lines in build.gradle file
apply plugin: 'application'
mainClassName = "com.example.demo.DemoApplication"
UNIT TESTING
Unit testing includes testing of smallest unit of code which usually are functions or methods. Unit testing is mostly done by developer of unit/method/function, because they understand the core of a function. The main goal of the developer is to cover code by unit tests.
It has a limitation that some functions cannot be tested through unit tests. Even after the successful completion of all the unit tests; it does not guarantee correct operation of the product. The same function can be used in few parts of the system while the unit test was written only for one usage.
FUNCTIONAL TESTING
It is a type of Black Box testing where testing will be done on the functional aspects of a product without looking into the code. Functional testing is mostly done by a dedicated Software tester. It will include positive, negative and BVA techniques using un standardized data for testing the specified functionality of product. Test coverage is conducted in an improved manner by functional tests than by unit tests. It uses application GUI for testing, so it’s easier to determine what exactly a specific part of the interface is responsible for rather to determine what a code is function responsible for.
I copied the Java.exe from
C:\Windows\System32
to
C:\Windows\SysWOW64
and it worked.
I'm using 64 bit Windows 8.
The value of the accept
attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like image/gif
, or a notation like image/*
that refers to all image
types, or a filename extension like .gif
. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*
, in this case
<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">
if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.
TextFX -> HTML Tidy -> Tidy: Reindent XML
Remember to have the HTML code selected before you do this.
Add "barryvdh/laravel-cors": "^0.7.3"
at the end of require
array inside composer.json
Save composer.json and run composer update
You are done !
Note that the value that you're formatting should be numeric. It doesn't look like it will take a string representation of a number and format is with commas.
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
It only requires the changes in permission of sock file.
sudo chmod 666 /var/run/docker.sock
this will work definately.
It can convert by
Convert.ToInt32 method
But it will throw an OverflowException if it the value is outside range of the Int32 Type. A basic test will show us how it works:
long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
int result;
foreach (long number in numbers)
{
try {
result = Convert.ToInt32(number);
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
number.GetType().Name, number,
result.GetType().Name, result);
}
catch (OverflowException) {
Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.",
number.GetType().Name, number);
}
}
// The example displays the following output:
// The Int64 value -9223372036854775808 is outside the range of the Int32 type.
// Converted the Int64 value -1 to the Int32 value -1.
// Converted the Int64 value 0 to the Int32 value 0.
// Converted the Int64 value 121 to the Int32 value 121.
// Converted the Int64 value 340 to the Int32 value 340.
// The Int64 value 9223372036854775807 is outside the range of the Int32 type.
Here there is a longer explanation.
You can use find
to find all matching files recursively:
$ find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \;
EDIT: what the '{}'
and \;
are?
The -exec
argument makes find execute rename
for every matching file found. '{}'
will be replaced with the path name of the file. The last token, \;
is there only to mark the end of the exec expression.
All that is described nicely in the man page for find:
-exec utility [argument ...] ;
True if the program named utility returns a zero value as its
exit status. Optional arguments may be passed to the utility.
The expression must be terminated by a semicolon (``;''). If you
invoke find from a shell you may need to quote the semicolon if
the shell would otherwise treat it as a control operator. If the
string ``{}'' appears anywhere in the utility name or the argu-
ments it is replaced by the pathname of the current file.
Utility will be executed from the directory from which find was
executed. Utility and arguments are not subject to the further
expansion of shell patterns and constructs.
You cannot use the syntax you have suggested. If you have a C99 compiler, though, you can do this:
int *p;
p = malloc(3 * sizeof p[0]);
memcpy(p, (int []){ 0, 1, 2 }, 3 * sizeof p[0]);
If your compiler does not support C99 compound literals, you need to use a named template to copy from:
int *p;
p = malloc(3 * sizeof p[0]);
{
static const int p_init[] = { 0, 1, 2 };
memcpy(p, p_init, 3 * sizeof p[0]);
}
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
I am not 100% certain, but I think this does what you want using prop.table. See mostly the last 3 lines. The rest of the code is just creating fake data.
set.seed(1234)
total_bill <- rnorm(50, 25, 3)
tip <- 0.15 * total_bill + rnorm(50, 0, 1)
sex <- rbinom(50, 1, 0.5)
smoker <- rbinom(50, 1, 0.3)
day <- ceiling(runif(50, 0,7))
time <- ceiling(runif(50, 0,3))
size <- 1 + rpois(50, 2)
my.data <- as.data.frame(cbind(total_bill, tip, sex, smoker, day, time, size))
my.data
my.table <- table(my.data$smoker)
my.prop <- prop.table(my.table)
cbind(my.table, my.prop)
I realize this couldn't have been the cause of the original problem, because Xcode 6 wasn't available then, but I'll leave the answer anyway in case it helps someone.
Xcode 6 now registers your bundle ID for you automatically, so you don't have to. It'll be somewhere in the list on a line starting with "Xcode iOS App ID".
Yes (write your own), something like the following complete function.
#include <stdio.h> /* only needed for the printf() in main(). */
#include <string.h>
/* Create a string of binary digits based on the input value.
Input:
val: value to convert.
buff: buffer to write to must be >= sz+1 chars.
sz: size of buffer.
Returns address of string or NULL if not enough space provided.
*/
static char *binrep (unsigned int val, char *buff, int sz) {
char *pbuff = buff;
/* Must be able to store one character at least. */
if (sz < 1) return NULL;
/* Special case for zero to ensure some output. */
if (val == 0) {
*pbuff++ = '0';
*pbuff = '\0';
return buff;
}
/* Work from the end of the buffer back. */
pbuff += sz;
*pbuff-- = '\0';
/* For each bit (going backwards) store character. */
while (val != 0) {
if (sz-- == 0) return NULL;
*pbuff-- = ((val & 1) == 1) ? '1' : '0';
/* Get next bit. */
val >>= 1;
}
return pbuff+1;
}
Add this main to the end of it to see it in operation:
#define SZ 32
int main(int argc, char *argv[]) {
int i;
int n;
char buff[SZ+1];
/* Process all arguments, outputting their binary. */
for (i = 1; i < argc; i++) {
n = atoi (argv[i]);
printf("[%3d] %9d -> %s (from '%s')\n", i, n,
binrep(n,buff,SZ), argv[i]);
}
return 0;
}
Run it with "progname 0 7 12 52 123"
to get:
[ 1] 0 -> 0 (from '0')
[ 2] 7 -> 111 (from '7')
[ 3] 12 -> 1100 (from '12')
[ 4] 52 -> 110100 (from '52')
[ 5] 123 -> 1111011 (from '123')
As others have said, it is not valid HTML.
It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.
ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?
I used to send some values from my listview
How to send
mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Favorite clickedObj = (Favorite) parent.getItemAtPosition(position);
Bundle args = new Bundle();
args.putString("tar_name", clickedObj.getNameTarife());
args.putString("fav_name", clickedObj.getName());
FragmentManager fragmentManager = getSupportFragmentManager();
TarifeDetayPopup userPopUp = new TarifeDetayPopup();
userPopUp.setArguments(args);
userPopUp.show(fragmentManager, "sam");
return false;
}
});
How to receive inside onCreate() method of DialogFragment
Bundle mArgs = getArguments();
String nameTrife = mArgs.getString("tar_name");
String nameFav = mArgs.getString("fav_name");
String name = "";
// Kotlin upload
val fm = supportFragmentManager
val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog
var args: Bundle? = null
args?.putString("title", model.title);
dialogFragment.setArguments(args)
dialogFragment.show(fm, "Sample Fragment")
// receive
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (getArguments() != null) {
val mArgs = arguments
var myDay= mArgs.getString("title")
}
}
I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.
So, you may get a chance with:
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)
As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.
For maven2 there isn't a way to do what you describe. For maven 3, there is. If you are using maven 3 please see another answer for this question
For maven 2 I'd recommend creating your own custom pom for the dependency that has your <exclusions>. For projects that need to use that dependency, set the dependency to your custom pom instead of the typical artifact. While that does not necessarily allow you exclude all transitive dependencies with a single <exclusion>, it does allow you only have to write your dependency once and all of your projects don't need to maintain unnecessary and long exclusion lists.
Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.
More information: http://php.net/manual/en/language.operators.errorcontrol.php
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
@fsockopen();
Use this query:
SELECT USER();
Or
SELECT CURRENT_USER;
For Xamarin Android align to the left of an object
int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
lp.AddRule( LayoutRules.CenterInParent, 1 );
lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id );
m_Button.LayoutParameters = lp;
if
isn't working then try "
instead."
Adding one more approach :
value = $(this).val().toLowerCase();
$("#product-search-result tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
Thanks for the answer of https://stackoverflow.com/a/65513726/889126, it gave me an idea to make a complete bash script as it is
export api_image_id=$(docker inspect --format="{{.Id}}" <image-name> | sed '/^[[:space:]]*$/d')
sudo docker exec -i -t ${api_image_id} /bin/bash
I need a specific container and make a script to extract some info from it in a quick sight.
Hope this would help others.
Honestly this is bad advice from npm
. An installation can run arbitrary scripts and running it with sudo
can be extremely dangerous! You could do sudo npm install -g less
to install it globally, but instead I would recommend updating your npm settings:
#~/.npmrc
prefix=~/.npm_modules
Then you can update your path:
#~/.bashrc or ~/.zshrc, etc.
export PATH=$PATH:$HOME/.npm_modules/bin
Then you don't require root permissions to perform the installation and you can still use the binary.
This would only apply to your user, however. If you want the entire system to be able to use the module you would have to tell everyone to add your path. More complicated and robust solutions would include adding a folder with node modules / binaries that a group could install to and adding that to everyone's path.
If you need just any one row from the right side
SELECT SuspReason, SiteID FROM(
SELECT SUSP.Susp_Visits.SuspReason, SUSP.Susp_Visits.SiteID, ROW_NUMBER()
OVER(PARTITION BY SUSP.Susp_Visits.SiteID) AS rn
FROM SUSP.Susp_Visits
LEFT OUTER JOIN DATA.Dim_Member ON SUSP.Susp_Visits.MemID = DATA.Dim_Member.MembershipNum
) AS t
WHERE rn=1
or just
SELECT SUSP.Susp_Visits.SuspReason, SUSP.Susp_Visits.SiteID
FROM SUSP.Susp_Visits WHERE EXISTS(
SELECT DATA.Dim_Member WHERE SUSP.Susp_Visits.MemID = DATA.Dim_Member.MembershipNum
)
raw.githubusercontent.com/username/repo-name/branch-name/path
Replace username
with the username of the user that created the repo.
Replace repo-name
with the name of the repo.
Replace branch-name
with the name of the branch.
Replace path
with the path to the file.
To reverse to go to GitHub.com:
GitHub.com/username/repo-name/directory-path/blob/branch-name/filename
You could do this two different ways. One is by using "as"
has_many :tasks, :as => :jobs
or
def jobs
self.tasks
end
Obviously the first one would be the best way to handle it.
this.arrToBeSorted = this.arrToBeSorted.sort(function(a, b){
return uppthis.sorrtingByArray.findIndex(x => x.Id == a.ByPramaeterSorted) - uppthis.sorrtingByArray.findIndex(x => x.Id == b.ByPramaeterSorted);
});
Use this function:
function zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if (in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))) {
continue;
}
$file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} elseif (is_file($file) === true) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} elseif (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
Example use:
zip('/folder/to/compress/', './compressed.zip');
$1
, $2
, $3
, ... are the positional parameters."$@"
is an array-like construct of all positional parameters, {$1, $2, $3 ...}
."$*"
is the IFS expansion of all positional parameters, $1 $2 $3 ...
.$#
is the number of positional parameters.$-
current options set for the shell.$$
pid of the current shell (not subshell).$_
most recent parameter (or the abs path of the command to start the current shell immediately after startup).$IFS
is the (input) field separator.$?
is the most recent foreground pipeline exit status.$!
is the PID of the most recent background command.$0
is the name of the shell or shell script.Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.
For a comprehensive index, please see the Reference Manual Variable Index.
Hemnath
If your variable is the percentage:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
If your close button is going to be text, this works very well for me:
#close {
position: fixed;
width: 70%; /* the width of the parent */
text-align: right;
}
#close span {
cursor: pointer;
}
Then your HTML
can just be:
<div id="close"><span id="x">X</span></div>
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
Send the passwordbox control as a parameter to your login command.
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
You need to install ENU\x64\SQLEXPRWT_x64_ENU.exe which is Express with Tools (RTM release. SP1 release can be found here).
As the page states
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express) This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
So install this and use the management studio included with it.
What you're looking for is n choose k. Basically:
For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).
You can run a container setting a shared directory (-v volume), and then run bash in that container. After this, you can interactively use mysql-client to execute the .sql file, from inside the container. obs: /my-host-dir/shared-dir is the .sql location in the host system.
docker run --detach --name=test-mysql -p host-port:container-port --env="MYSQL_ROOT_PASSWORD=my-root-pswd" -v /my-host-dir/shared-dir:/container-dir mysql:latest
docker exec -it test-mysql bash
Inside the container...
mysql -p < /container-dir/file.sql
Custom parameters:
If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.
157/32
is an integer division because all numerical literals are integers unless otherwise specified with a suffix (d
for double l
for long)
the division is rounded down (to 4) before it is converted to a double (4.0) which is then rounded up (to 4.0)
if you use a variables you can avoid that
double a1=157;
double a2=32;
int total = (int) Math.ceil(a1/a2);
This is a rehash of the previous answer but it's more likely to work on different mongodb versions.
db.collection.find().limit(1).sort({$natural:-1})
Instead of using this
DB_HOST=localhost
DB_DATABASE=wdcollect
DB_USERNAME=root
DB_PASSWORD=
USE this
DB_HOST=localhost
DB_DATABASE=wdcollect
DB_USERNAME=root
DB_PASSWORD=''
Alternativly this option uses the native windows progress bar...
$FOF_CREATEPROGRESSDLG = "&H0&"
$objShell = New-Object -ComObject "Shell.Application"
$objFolder = $objShell.NameSpace($DestLocation)
$objFolder.CopyHere($srcFile, $FOF_CREATEPROGRESSDLG)
Just before the closing body tag, as stated on
http://developer.yahoo.com/performance/rules.html#js_bottom
Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
key
is a function that will be called to transform the collection's items before they are compared. The parameter passed to key
must be something that is callable.
The use of lambda
creates an anonymous function (which is callable). In the case of sorted
the callable only takes one parameters. Python's lambda
is pretty simple. It can only do and return one thing really.
The syntax of lambda
is the word lambda
followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while
, for
, if
and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.
We can compare the use of lambda with that of def to create a function.
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2
lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.
variable
is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.
As the used variables from outside the lamda have to be (implicitly) final, you have to use something like AtomicInteger
or write your own data structure.
See https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#accessing-local-variables.