The following worked, but only after I upgraded PSEXEC to 2.1 from Microsoft.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] "LocalAccountTokenFilterPolicy"=dword:00000001 See: http://forum.sysinternals.com/topic10924.html
I had a slightly older version that didn't work. I used it to do some USMT work via Dell kace, worked a treat :)
Create a Name.bat file that has the following line in it.
taskkill /F /IM wscript.exe /T
Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.
This fixes some issues with Blorgbeard's answer (but is untested):
@echo off
cd /d "c:\Program files\IIS Express"
start "" iisexpress /path:"C:\FormsAdmin.Site" /port:8088 /clr:v2.0
timeout 10
start http://localhost:8088/default.aspx
pause
If you want to delete lines 5 through 10 and 12:
sed -e '5,10d;12d' file
This will print the results to the screen. If you want to save the results to the same file:
sed -i.bak -e '5,10d;12d' file
This will back the file up to file.bak
, and delete the given lines.
Note: Line numbers start at 1. The first line of the file is 1, not 0.
I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.
Also, the project is mostly dormant... the last release was in 2004.
For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.
flush();
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. It will update or insert into your tables in the running transaction, but it may not commit those changes.
You need to flush in batch processing otherwise it may give OutOfMemoryException.
Commit();
Commit will make the database commit. When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. So, you should commit but it also ends the unit of work (transaction.commit()
).
Unfortunately, you need to manually construct the query parameters, because as far as I know, there is no built-in bind
method for binding a list
to an IN
clause, similar to Hibernate's setParameterList()
. However, you can accomplish the same with the following:
Python 3:
args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
cursor.execute(sql, args)
Python 2:
args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(map(lambda x: '%s', args))
sql = sql % in_p
cursor.execute(sql, args)
I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf
$("#MyTableData").on({
mouseenter: function(){
//stuff to do on mouse enter
$(this).css({'color':'red'});
},
mouseleave: function () {
//stuff to do on mouse leave
$(this).css({'color':'blue'});
}},'tr');
You can do something like this:
val ans = (exp1 == exp2) then "yes" ?: "no"
by using this extension:
infix fun<T> Boolean.then(first: T): T? = if (this) first else null
P.S: Dont modify above infix function to accept first: T?
, the expression will become logically incorrect. Eg: If you modify it to accept nullable first: T?
, then val ans = (true == true) then null ?: "abcd"
, ans
will be "abcd"
, which would not be correct.
git log --follow [file]
will show you the history through renames.
INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);
It was fixed this kind of error after migrate to AndroidX
For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.
You have two ways to address this:
_optim_peek_user_binds = false
Of course underscore parameters should only be set if advised by oracle support
You must check if result returned by mysql_query is false.
$r = mysql_qyery("...");
if ($r) {
mysql_fetch_assoc($r);
}
You can use @mysql_fetch_assoc($r)
to avoid error displaying.
I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)
Now, you can use standard string function find
to check the output string output
.
Well I guess you can use checked="false". That is the html way to leave a checkbox unchecked. You can refer to http://www.w3schools.com/jsref/dom_obj_checkbox.asp.
Try this.
To get the data from the UserDefaults.
var defaults = NSUserDefaults.standardUserDefaults()
var dict : NSDictionary = ["key":"value"]
var array1: NSArray = dict.allValues // Create a dictionary and assign that to this array
defaults.setObject(array1, forkey : "MyKey")
var myarray : NSArray = defaults.objectForKey("MyKey") as NSArray
println(myarray)
If you simply need to answer "y" to all the overwrite prompts, try this:
y | mv srcdir/* targetdir/
First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:
cd ~/Documents/python
Now, you should be able to execute your file:
python gameover.py
I had the same problem just with switching the background images with reasonable sizes. I got better results with setting the ImageView to null before putting in a new picture.
ImageView ivBg = (ImageView) findViewById(R.id.main_backgroundImage);
ivBg.setImageDrawable(null);
ivBg.setImageDrawable(getResources().getDrawable(R.drawable.new_picture));
Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.
To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.
Although a user may set the date and time together manually, they cannot use the GUI to set both.
If you are receiving that error even after creating a new user and assigning them the database previledges, then the one last thing to look at is to check if the users have been assigned the preiveledges in the database.
To do this log into to your mysql(This is presumably its the application that has restricted access to the database but you as a root can be ablr to access your database table via mysql -u user -p)
commands to apply
mysql -u root -p
password: (provide your database credentials)
on successful login
type
use mysql;
from this point check each users priveledges if it is enabled from the db table as follows
select User,Grant_priv,Host from db;
if the values of the Grant_priv col for the created user is N update that value to Y with the following command
UPDATE db SET Grant_priv = "Y" WHERE User= "your user";
with that now try accessing the app and making a transaction with the database.
What cfengineers said, except it sounds like you will want to sort it as well.
select columns
from table
where (
column like 'a%'
or column like 'b%' )
order by column
Perhaps it would be a good idea for you to check out some tutorials on SQL, it's pretty interesting.
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.
Just put a line break into your text.
You don't add lines as a method. Multiline just supports the use of line breaks.
If you are releasing, use the keystore you used to export your app with and not the debug.keystore.
If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).
var exceptionList = new List<string> { "exception1", "exception2" };
var query = myEntities.MyEntity
.Select(e => e.Name)
.Where(e => !exceptionList.Contains(e.Name));
If you're excluding based on another database query using Except
might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)
var exceptionList = myEntities.MyOtherEntity
.Select(e => e.Name);
var query = myEntities.MyEntity
.Select(e => e.Name)
.Except(exceptionList);
This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).
I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:
$(".bgHeaderH2").text();
On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.
C++ code:
void foo(int a, int b, int* c, int* d)
{
*c = a / b;
*d = a % b;
}
x86 code:
__Z3fooiiPiS_:
LFB4:
movq %rdx, %r8
movl %edi, %edx
movl %edi, %eax
sarl $31, %edx
idivl %esi
movl %eax, (%r8)
movl %edx, (%rcx)
ret
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
I tried using this example but it failed miserably. Every time I use to invoke finish()/ finishactivity() inside a handler, I end up with this menacing java.lang.IllegalAccess Exception
. i'm not sure how did it work for the one who posed the question.
Instead the solution I found was that create a method in your activity such as
void kill_activity()
{
finish();
}
Invoke this method from inside the run method of the handler. This worked like a charm for me. Hope this helps anyone struggling with "how to close an activity from a different thread?".
I solved my problem simply using ng-init
for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
Explain what video describe to resolve problem
After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
If you have more than 1 DB server, add "i++" to file and continue add new config as above
I had an issue with XCode 10.2 specifying the correct iOS simulator version number, so used:
react-native run-ios --simulator='iPhone X (com.apple.CoreSimulator.SimRuntime.iOS-12-1)'
The best way is actually to create a new Project from scratch, then go into the folder with the project files you want to copy over (project, form1, everything except folders). Rename the files (Except for form1 files) for example: I copied Ch4Ex1 files into my Ch4Ex2 project but first renamed the files to Ch4Ex2. Copy and paste those files into the Solution Explorer for the new project in Visual Studio. Then just overwrite the files and you should be good to go!
Old thread but I hope it helps anyone looking for this answer!
Try replacing apt-get
with yum
as Amazon Linux based AMI uses the yum
command instead of apt-get
.
To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.
In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline
would not work.
I was just having the same issue and suggest you use Jupyter Notebook for the visualization.
This will do the work either for Kotlin or Java project.
Step 1 - Locate build.gradle(Module:app) under the Gradle Scripts
Step 2 - add multiDexEnabled true see below:
compileSdkVersion 29
defaultConfig {
applicationId "com.example.appname"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled true //addded
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Step 3 - add the multidex dependency
dependencies {
implementation 'com.android.support:multidex:2.0.0' //added
}
Finally, sync your project.. Enjoy!
I just add this because it worked for me, i install composer with the developer option activate (just check the box in the installer)
https://getcomposer.org/Composer-Setup.exe
I think this problem may occurs when you add a new version of php to your wamp server. If you do this, you have to check if the extension_dir variable is configure to "env".
Then check if the php_openssl.dll exist in your phpx.x/ext folder. If there is not php_openssl.dll, you have to download it here : http://www.telecharger-dll.fr/dll-php_openssl.dll.html
If it still not working, check if your apache server use the good php.ini file by running the following cmd command :
php --ini
Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File: C:\wamp64\bin\php\php7.4.7x64\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
If the loaded configuration file return (none), you have to check your appache/apache2.4.41/conf/httpd.conf file is configure with the proper phpIniDir and the correct module.
It must be something like this :
PHPIniDir "${APACHE_DIR}/bin"
LoadModule php7_module "${INSTALL_DIR}/bin/php/php7.4.7x64/php7apache2_4.dll"
Then restart apache and check the "apache/apache2.4.41/bin/php.ini" (wich is the one configure above by PHPIniDir) it must me like
try FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, txtCompanyID)
I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though
shlex has a .split()
function. It differs from str.split()
in that it does not preserve quotes and treats a quoted phrase as a single word:
>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']
NB: it works well for Unix-like command line strings. It doesn't work for natural-language processing.
With ES6, we now have a simple way to create an Array from a NodeList: the Array.from()
function.
// nl is a NodeList
let myArray = Array.from(nl)
Sometime in the future .NET4.6
//for Double
double inputValues = double.Parse(Console.ReadLine());
//for Int
int inputValues = int.Parse(Console.ReadLine());
In your User
model, add the following line in the User
class:
public $timestamps = true;
Now, whenever you save or update a user, Laravel will automatically update the created_at
and updated_at
fields.
Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s
. The problem is that the format you have used is not the same as Laravel uses for the created_at
field.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.
Assembly.GetTypes()
works on the local assembly, or you can load an assembly first then call GetTypes()
on it.
You have to load the url helper to access that function. Either you add
$this->load->helper('url');
somewhere in your controller.
Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like
$autoload['helper'] = array('url');
has 'url'
in that array (as shown above).
The componentDidUpdate
signature is void::componentDidUpdate(previousProps, previousState)
. With this you will be able to test which props/state are dirty and call setState
accordingly.
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}
Technically, i don't think that there is a difference, because properties are just wrappers around fields created by the user or automatically created by the compiler.The purpose of properties is to enforce encapsuation and to offer a lightweight method-like feature. It's just a bad practice to declare fields as public, but it does not have any issues.
my develop environment is
above answers not fully work for me
after try, my finally working solution is:
let indent_large_enought_to_hidden:CGFloat = 10000
cell.separatorInset = UIEdgeInsetsMake(0, indent_large_enought_to_hidden, 0, 0) // indent large engough for separator(including cell' content) to hidden separator
cell.indentationWidth = indent_large_enought_to_hidden * -1 // adjust the cell's content to show normally
cell.indentationLevel = 1 // must add this, otherwise default is 0, now actual indentation = indentationWidth * indentationLevel = 10000 * 1 = -10000
I had the same problem as you though I have followed a different guide: http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
The strange part is that, in this guide I have used, I should not have any problem with compatibility between versions (1.x against 2.x) because following the guide you use the jersey 1.8.x on pom.xml
and in the web.xml
you refer to a class (com.sun.jersey.spi.container.servlet.ServletContainer
) as said before of 1.x version. So as I can infer this should be working.
My guess is because I'm using JDK 1.7 this class does not exist anymore.
After, I tried to resolve with the answers before mine, did not helped, I have made changes on the pom.xml
and on the web.xml
the error changed to: java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Which supposedly should be exist!
As result of this error, I found a "new" solution: http://marek.potociar.net/2013/06/13/jax-rs-2-0-and-jersey-2-0-released/
With Maven (archetypes), generate a jersey project, likes this:
mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.0
And it worked for me! :)
If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r
This is how I got rid of the error:
WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}
In your nodeconfig.json, the version must be a String, not an integer.
So instead of using "version": 11
use "version": "11"
(note the double quotes).
A full example of a working nodecondig.json file for a RemoteWebDriver:
{
"capabilities":
[
{
"platform": "WIN8_1",
"browserName": "internet explorer",
"maxInstances": 1,
"seleniumProtocol": "WebDriver"
"version": "11"
}
,{
"platform": "WIN7",
"browserName": "chrome",
"maxInstances": 4,
"seleniumProtocol": "WebDriver"
"version": "40"
}
,{
"platform": "LINUX",
"browserName": "firefox",
"maxInstances": 4,
"seleniumProtocol": "WebDriver"
"version": "33"
}
],
"configuration":
{
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"maxSession": 3,
"port": 5555,
"host": ip,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": {your-ip-address}
}
}
you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.
Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html
If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
PHP will work only on the .php
file extension.
If you are on Apache you can also set, in your httpd.conf
file, the extensions for PHP. You'll have to find the line:
AddType application/x-httpd-php .php .html
^^^^^
and add how many extensions, that should be read with the PHP interpreter, as you want.
Do not write tests for private methods. This defeats the point of unit tests.
Example
class SomeClass {
public addNumber(a: number, b: number) {
return a + b;
}
}
The test for this method should not need to change if later the implementation changes but the behaviour
of the public API remains the same.
class SomeClass {
public addNumber(a: number, b: number) {
return this.add(a, b);
}
private add(a: number, b: number) {
return a + b;
}
}
Don't make methods and properties public just in order to test them. This usually means that either:
I've figured out how to work around this issue without mixing parent and sub scope data.
Set a ng-if
on the the ng-include
element and set it to a scope variable.
For example :
<div ng-include="{{ template }}" ng-if="show"/>
In your controller, when you have set all the data you need in your sub scope, then set show to true
. The ng-include
will copy at this moment the data set in your scope and set it in your sub scope.
The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.
Max
I use them to break up complex queries, especially complex joins and sub-queries. I find I'm using them more and more as 'pseudo-views' to help me get my head around the intent of the query.
My only complaint about them is they cannot be re-used. For example, I may have a stored proc with two update statements that could use the same CTE. But the 'scope' of the CTE is the first query only.
Trouble is, 'simple examples' probably don't really need CTE's!
Still, very handy.
For C, at least, per C11 6.7.5:
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
for an object, causes storage to be reserved for that object;
for a function, includes the function body;
for an enumeration constant, is the (only) declaration of the identifier;
for a typedef name, is the first (or only) declaration of the identifier.
Per C11 6.7.9.8-10:
An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.
So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.
Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).
So, if you define an automatic variable without specifying an initial value for it, such as:
int myfunc(void) {
int myvar;
...
You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.
Solution based on configuration only, with a ThresoldFilter and LevelFilters to keep things really simple to understand :
<configuration>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>%date %level [%thread] %logger %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<target>System.out</target>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
</filter>
<encoder>
<pattern>%date %level [%thread] %logger %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="STDERR" />
</root>
</configuration>
Let's use some java 8 feature:
IntStream.iterate(10, x -> x + 10).limit(5)
.forEach(System.out::println);
If you need to store the numbers you can collect them into a collection eg:
List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
.boxed()
.collect(Collectors.toList());
And some delay added:
IntStream.iterate(10, x -> x + 10).limit(5)
.forEach(x -> {
System.out.println(x);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Do something with the exception
}
});
On a slightly different note, I had to make a virtual device without GSM Modem Support so that the internet on my emulator would work.
You can compile a C# program :
c: > csc Hello.cs
You can run the program
c: > Hello
See this table.
A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.
A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.
You could use list comprehensions to bring the item in your tuple into a list:
conn = mysql.connector.connect()
cursor = conn.cursor()
sql = "SELECT column_name FROM db.table_name;"
cursor.execute(sql)
results = cursor.fetchall()
# bring the first item of the tuple in your results here
item_0_in_result = [_[0] for _ in results]
import os,shutil
current_path = "" ## source path
new_path = "" ## destination path
os.chdir(current_path)
for files in os.listdir():
os.rename(files, new_path+'{}'.format(f))
shutil.move(files, new_path+'{}'.format(f)) ## to move files from
different disk ex. C: --> D:
If one just want to schedule a countdown until a time in the future with regular notifications on intervals along the way, you can use the CountDownTimer class that is available since API level 1.
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
editText.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
editText.setText("Done");
}
}.start();
You have two records in your json file, and json.loads()
is not able to decode more than one. You need to do it record by record.
See Python json.loads shows ValueError: Extra data
OR you need to reformat your json to contain an array:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
would be acceptable again. But there cannot be several top level objects.
I could get solution for such a similar problem with addition of a simple line
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.
CryptoJS is a crypto library which can generate md5 hash among others:
Usage with Script tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script>
var hash = CryptoJS.MD5("Message");
alert(hash);
</script>
Alternatively with ES6:
npm install crypto-js
import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());
You can also use modular imports:
var MD5 = require("crypto-js/md5");
console.log(MD5("Message").toString());
Github: https://github.com/brix/crypto-js
CDN: https://cdnjs.com/libraries/crypto-js
I have Samsung Galaxy S3 and it was not showing in the "Remote devices" tab nor in chrome://inspect. The device did show in Windows's Device Manager as GT-I9300, though. What worked for me was:
cmd.exe
cd "C:\Program Files (x86)\ClockworkMod\Universal Adb Driver"
adb devices
I'm not sure if it affected the whole flow somehow, but at some point I've installed, and later uninstalled the drivers from Samsung: http://www.samsung.com/us/support/downloads/ > Mobile > Phones > Galaxy S > S III > Unlocked > http://www.samsung.com/us/support/owners/product/galaxy-s-iii-unlocked#downloads
Make sure to use the !important attribute. This dramatically increases the likelihood your styles are retained when printed.
#example1 {
background:url(image.png) no-repeat !important;
}
#example2 {
background-color: #123456 !important;
}
I think if you have MyEclipse, it adds a label to the Project Properties page which contains the total number of source code lines. Might not help you as MyEclipse is not free though.
Unfortunately, that wasn't enough in my case so I wrote a source analyzer to gather statistics not gathered by other solutions (for example the metrics mentioned by AlbertoPL).
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
I had this problem where I couldn't unlock a file from the client side. I decided to go to the sever side which was much simpler.
On SVN Server:
Locate locks
svnadmin lslocks /root/of/repo
(in my case it was var/www/svn/[name of Company])
You can add a specific path to this by svnadmin lslocks /root/of/repo "path/to/file"
Remove lock
svnadmin rmlocks /root/of/repo “path/to/file”
That's it!
df = df1.drop_duplicates().merge(df2.drop_duplicates(), on=df2.columns.to_list(),
how='left', indicator=True)
df.loc[df._merge=='left_only',df.columns!='_merge']
Note that drop duplicated is used to minimize the comparisons. It would work without them as well. The best way is to compare the row contents themselves and not the index or one/two columns and same code can be used for other filters like 'both' and 'right_only' as well to achieve similar results. For this syntax dataframes can have any number of columns and even different indices. Only the columns should occur in both the dataframes.
pandas.concat()
coupled with drop_duplicated()
is not ideal because it will also get rid of the rows which may be only in the dataframe you want to keep and are duplicated for valid reasons.#sort dataframe by col
sort.df <- with(df, df[order(sortbythiscolumn) , ])
#can also sort by more than one variable: sort by col1 and then by col2
sort2.df <- with(df, df[order(col1, col2) , ])
#sort in reverse order
sort2.df <- with(df, df[order(col1, -col2) , ])
Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference
dialog.
Be sure that the new reference has the Copy Local = True
.
The Add Reference
dialog could be opened right-clicking on the References item in your project in Solution Explorer
UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:
It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.
Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.
Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):
var x = function(){_x000D_
var y = function() {_x000D_
alert('fired y');_x000D_
}_x000D_
};_x000D_
_x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
var x = function(){_x000D_
var y = function() {_x000D_
alert('fired y');_x000D_
}_x000D_
};_x000D_
_x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
use Latin1_General_CS as your collation in your sql db
Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.
Commands are first read from /etc/zshenv this cannot be overridden.
Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
former affects all startup files, while the second only affects global
startup files (those shown here with an path starting with a /). If
one of the options is unset at any point, any subsequent startup
file(s) of the corresponding type will not be read. It is also possi-
ble for a file in $ZDOTDIR to re-enable GLOBAL_RCS. Both RCS and
GLOBAL_RCS are set by default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login
shell, commands are read from /etc/zprofile and then $ZDOTDIR/.zpro-
file. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if the shell is a login
shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.
From this we can see the order files are read is:
/etc/zshenv # Read for every shell
~/.zshenv # Read for every shell except ones started with -f
/etc/zprofile # Global config for login shells, read before zshrc
~/.zprofile # User config for login shells
/etc/zshrc # Global config for interactive shells
~/.zshrc # User config for interactive shells
/etc/zlogin # Global config for login shells, read after zshrc
~/.zlogin # User config for login shells
~/.zlogout # User config for login shells, read upon logout
/etc/zlogout # Global config for login shells, read after user logout file
You can get more information here.
Update in 2019:
This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.
Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!
iBeacon uses Bluetooth Low Energy(LE) to keep aware of locations, and the distance/range of Bluetooth LE is 160ft (http://en.wikipedia.org/wiki/Bluetooth_low_energy).
IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.
The method array.toString()
actually calls array.join()
which result in a string concatenated by commas. ref
var array = ['a','b','c','d','e','f'];_x000D_
document.write(array.toString()); // "a,b,c,d,e,f"
_x000D_
Also, you can implicitly call Array.toString()
by making javascript coerce the Array
to an string
, like:
//will implicitly call array.toString()
str = ""+array;
str = `${array}`;
The join() method joins all elements of an array into a string.
It accepts a separator
as argument, but the default is already a comma ,
str = arr.join([separator = ','])
var array = ['A', 'B', 'C'];
var myVar1 = array.join(); // 'A,B,C'
var myVar2 = array.join(', '); // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join(''); // 'ABC'
If any element of the array is undefined or null , it is treated as an empty string.
It is available pretty much everywhere today, since IE 5.5 (1999~2000).
Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.
That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.
While we are on the topic you must check this out. Its an interesting read.
I don't there there is any DataSource
for the gridview
Though you have DataBind
in your code as
gvdetails.DataBind();
A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.
Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.
For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.
What about casting to Number in Javascript using the Unary (+) Operator
lat: 12.23
lat: +12.23
Depends on the use case. Here is a fullchart what works and what not: parseInt vs unary plus - when to use which
SuppressFinalize
should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this
object was cleaned up fully.
The recommended IDisposable
pattern when you have a finalizer is:
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// called via myClass.Dispose().
// OK to use any private object references
}
// Release unmanaged resources.
// Set large fields to null.
disposed = true;
}
}
public void Dispose() // Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
Dispose(false);
}
}
Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize
tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.
The SuppressFinalize
optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize
on other objects mind you. That's a serious defect waiting to happen.
Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable
, but if you have a finalizer you should implement IDisposable
to allow deterministic cleanup of your class.
Most of the time you should be able to get away with IDisposable
to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.
Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable
classes in order to test that code has disposed their IDisposable
object properly.
public void Dispose() // Implement IDisposable
{
Dispose(true);
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
#if DEBUG
~MyClass() // the finalizer
{
Dispose(false);
}
#endif
In case of Linear Regression the outcome is continuous while in case of Logistic Regression outcome is discrete (not continuous)
To perform Linear regression we require a linear relationship between the dependent and independent variables. But to perform Logistic regression we do not require a linear relationship between the dependent and independent variables.
Linear Regression is all about fitting a straight line in the data while Logistic Regression is about fitting a curve to the data.
Linear Regression is a regression algorithm for Machine Learning while Logistic Regression is a classification Algorithm for machine learning.
Linear regression assumes gaussian (or normal) distribution of dependent variable. Logistic regression assumes binomial distribution of dependent variable.
I implemented all the previous answers and still had one view that did not work correctly.
It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.
After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.
Something that is now available in maven as well is
mvn goal --no-snapshot-updates
or in short
mvn goal -nsu
If using httplib.HTTPSConnection:
Please take a look at:
This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter. You can use:
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.
Try Eric Meyer's reset.css.
Use following property same as table and its fully dynamic:
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed; /* optional, for equal spacing */_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid pink;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz klxjgkldjklg </li>_x000D_
<li>baz</li>_x000D_
<li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
May be its solve your issue.
If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.
But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application
class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application
instead.
I'd suggest reading this article about context to better figure it out what context you need.
You can use \begin{flalign}
, like the example bellow:
\begin{flalign}
&f(x) = -1.25x^{2} + 1.5x&
\end{flalign}
Sometimes I resolved similar situations (such as using pandas.apply method) using closures
In order to use them, you define a function which dynamically defines and returns a wrapper for your function, effectively making one of the parameters a constant.
Something like this:
def add(x, y):
return x + y
def add_constant(y):
def f(x):
return add(x, y)
return f
Then, add_constant(y)
returns a function which can be used to add y
to any given value:
>>> add_constant(2)(3)
5
Which allows you to use it in any situation where parameters are given one at a time:
>>> map(add_constant(2), [1,2,3])
[3, 4, 5]
edit
If you do not want to have to write the closure function somewhere else, you always have the possibility to build it on the fly using a lambda function:
>>> map(lambda x: add(x, 2), [1, 2, 3])
[3, 4, 5]
Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link
function of the directive.
There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls
Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.
EDIT: Rather than using $(element)
, you can make use of angular.element(element)
when using AngularJS with jQuery
This is more of a stopgap 'quick and dirty' solution similar to the one Matthew Fox suggests, this time using JavaScript.
In JavaScript you can just offset the lat and long of all of your locations by adding a small random offset to both e.g.
myLocation[i].Latitude+ = (Math.random() / 25000)
(I found that dividing by 25000 gives enough separation but doesn't move the marker significantly from the exact location e.g. a specific address)
This makes a reasonably good job of offsetting them from one another, but only after you've zoomed in closely. When zoomed out, it still won't be clear that there are multiple options for the location.
Click "Project" at the top. Then click " Properties" -> Signing -> Unchecked [Sign the ClickOnce manifests] is now working
As no one is talking about the why part, I'm gonna answer it.
Why this JSON.stringify
returns an empty object?
> JSON.stringify(error);
'{}'
Answer
From the document of JSON.stringify(),
For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.
and Error
object doesn't have its enumerable properties, that's why it prints an empty object.
I wanted to add my solution since the accepted one didn't quite work for me.
I needed to add a directive but also keep mine on the element.
In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.
angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
return {
priority: 1001,
controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
// controller code here
}],
compile: function(element, attributes){
var compile = false;
//check to see if the target directive was already added
if(!element.attr('ng-style')){
//add the target directive
element.attr('ng-style', "{'width':'200px'}");
compile = true;
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
if(compile){
$compile(iElement)(scope);
}
}
};
}
};
}]);
First, convert the string into a timestamp:
$timestamp = strtotime($string);
Then do a
date("Y-m-d H:i:s", $timestamp);
Your are probably looking for eval $var
.
You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)
So to insert Employee / Department pairs that do not currently exist you might try something like the following.
CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e
on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
Try this:
Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
With REGEXP_SUBSTR is as simple as:
SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;
There's two standard library ways to find the most frequent value in a list:
from statistics import mode
most_common = mode([3, 2, 2, 2, 1, 1]) # 2
most_common = mode([3, 2]) # StatisticsError: no unique mode
collections.Counter.most_common
:
from collections import Counter
most_common, count = Counter([3, 2, 2, 2, 1, 1]).most_common(2) # 2, 3
(most_common_1, count_1), (most_common_2, count_2) = Counter([3, 2, 2]).most_common(2) # (2, 2), (3, 1)
So in the case of the question, the second one would be the right choice. As a side note, both are identical in terms of performance.
I didnt want Static Url. I have AjaxFactory for doing all ajax operations. I am getting url from the factory and binding it as follows.
<a target="_self" href="{{ file.downloadUrl + '/' + order.OrderId + '/' + fileName }}" download="{{fileName}}">{{fileName}}</a>
Thanks @AhlemMustapha
It is work, I hope help you
.btn:focus, .btn:focus:active {
outline: none;
}
This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.
public final class MyFragment extends Fragment {
private TextView vstup;
private Bundle savedState = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.whatever, null);
vstup = (TextView)v.findViewById(R.id.whatever);
/* (...) */
/* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
/* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
if(savedInstanceState != null && savedState == null) {
savedState = savedInstanceState.getBundle(App.STAV);
}
if(savedState != null) {
vstup.setText(savedState.getCharSequence(App.VSTUP));
}
savedState = null;
return v;
}
@Override
public void onDestroyView() {
super.onDestroyView();
savedState = saveState(); /* vstup defined here for sure */
vstup = null;
}
private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
Bundle state = new Bundle();
state.putCharSequence(App.VSTUP, vstup.getText());
return state;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
/* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
/* => (?:) operator inevitable! */
outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
}
/* (...) */
}
Alternatively, it is always a possibility to keep the data displayed in passive View
s in variables and using the View
s only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.
How to convert date to string and to date again?
LocalDate.now().toString()
2017-01-23
…and…
LocalDate.parse( "2017-01-23" )
The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.
Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.
If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.
That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse
and LocalDate::toString
without specifying a formatting pattern.
String s = ld.toString() ;
To parse:
LocalDate ld = LocalDate.parse( s ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You can also do this easily in Pandas, if your data is represented in a Dataframe, as described here:
http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#scatter-plot
my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list
This will print:
['foobar', 'fobbar', 'fazbar', 'funkbar']
You may fill the column by double-clicking on the bottom right hand corner of the cell which you want to copy from (the point on the box that you would otherwise drag) and it will be applied to whole column.
NB: This doesn't work if you have the filter applied, nor if there is already something already in the cells below.
The answers are correct but don't mention how to sync code between the public repo and the fork.
Here is the full workflow (we've done this before open sourcing React Native):
First, duplicate the repo as others said (details here):
Create a new repo (let's call it private-repo
) via the Github UI. Then:
git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git
Clone the private repo so you can work on it:
git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master
To pull new hotness from the public repo:
cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master
Awesome, your private repo now has the latest code from the public repo plus your changes.
Finally, to create a pull request private repo -> public repo:
Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:
git clone https://github.com/yourname/the-fork.git
cd the-fork
git remote add private_repo_yourname https://github.com/yourname/private-repo.git
git checkout -b pull_request_yourname
git pull private_repo_yourname master
git push origin pull_request_yourname
Now you can create a pull request via the Github UI for public-repo, as described here.
Once project owners review your pull request, they can merge it.
Of course the whole process can be repeated (just leave out the steps where you add remotes).
I think you're x86-64 install does not have the i386 runtime linker. The ENOENT is probably due to the OS looking for something like /lib/ld.so.1 or similar. This is typically part of the 32-bit glibc runtime, and while I'm not directly familiar with Ubuntu, I would assume they have some sort of 32-bit compatibility package to install. Fortunately gzip only depends on the C library, so that's probably all you'll need to install.
As others have mentioned, the NET::ERR_CERT_COMMON_NAME_INVALID
error is occurring because the generated certificate does not include the SAN (subjectAltName
) field.
RFC2818 has deprecated falling back to the commonName
field since May of 2000. The use of the subjectAltName
field has been enforced in Chrome since version 58 (see Chrome 58 deprecations).
OpenSSL accepts x509v3 configuration files to add extended configurations to certificates (see the subjectAltName field for configuration options).
I created a self-signed-tls bash script with straightforward options to make it easy to generate certificate authorities and sign x509 certificates with OpenSSL (valid in Chrome using the subjectAltName
field).
The script will guide you through a series of questions to include the necessary information (including the subjectAltName
field). You can reference the README.md for more details and options for automation.
Be sure to restart chrome after installing new certificates.
chrome://restart
You want to use the stringizing operator:
#define STRING(s) #s
int main()
{
const char * cstr = STRING(abc); //cstr == "abc"
}
As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.
numpy already allows the creation of arrays of all ones or all zeros very easily:
e.g. numpy.ones((2, 2))
or numpy.zeros((2, 2))
Since True
and False
are represented in Python as 1
and 0
, respectively, we have only to specify this array should be boolean using the optional dtype
parameter and we are done.
numpy.ones((2, 2), dtype=bool)
returns:
array([[ True, True],
[ True, True]], dtype=bool)
UPDATE: 30 October 2013
Since numpy version 1.8, we can use full
to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):
numpy.full((2, 2), True, dtype=bool)
UPDATE: 16 January 2017
Since at least numpy version 1.12, full
automatically casts results to the dtype
of the second parameter, so we can just write:
numpy.full((2, 2), True)
This is how I rotate 360 in right direction.
[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveLinear
animations:^{
[imageIndView setTransform:CGAffineTransformRotate([imageIndView transform], M_PI-0.00001f)];
} completion:nil];
You are using an old version of the date picker js. Upgrade datepicker js with latest one.
Replace your bootstrap-datetimepicker.min.js file with this will work..
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.3/js/bootstrap-datetimepicker.min.js"></script>
In your components.module.ts you should import IonicModule like this:
import { IonicModule } from '@ionic/angular';
Then import IonicModule like this:
imports: [
CommonModule,
IonicModule
],
so your components.module.ts will be like this:
import { CommonModule } from '@angular/common';
import {PostComponent} from './post/post.component'
import { IonicModule } from '@ionic/angular';
@NgModule({
declarations: [PostComponent],
imports: [
CommonModule,
IonicModule
],
exports: [PostComponent]
})
export class ComponentsModule { }```
If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:
for (int i = 1; i < 100000; i *= 2) {
String s = "00" + i;
System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
}
Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)
Want to format it automatically when you save the file???
then Goto Window > Preferences > Java > Editor > Save Actions
and configure your save actions.
Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc
Then just Select
:
var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();
(edit) Actually - the names could be inferred in this case, so you could use:
var list = source.Select(s=>new { s.ID, s.Name }).ToList();
which saves a few electrons...
With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:
JS file:
var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();
ToEndDate.setDate(ToEndDate.getDate()+365);
$('.from_date').datepicker({
weekStart: 1,
startDate: '01/01/2012',
endDate: FromEndDate,
autoclose: true
})
.on('changeDate', function(selected){
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
$('.to_date').datepicker('setStartDate', startDate);
});
$('.to_date')
.datepicker({
weekStart: 1,
startDate: startDate,
endDate: ToEndDate,
autoclose: true
})
.on('changeDate', function(selected){
FromEndDate = new Date(selected.date.valueOf());
FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
$('.from_date').datepicker('setEndDate', FromEndDate);
});
HTML:
<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text"
And do not forget to include bootstrap datepicker.js and .css files aswell.
While you are looping in an array with each
and if you want to access another array in the context of the current item you do it like this.
Here is the example data.
[ { name: 'foo', attr: [ 'boo', 'zoo' ] }, { name: 'bar', attr: [ 'far', 'zar' ] } ]
Here is the handlebars to get the first item in attr
array.
{{#each player}} <p> {{this.name}} </p> {{#with this.attr}} <p> {{this.[0]}} </p> {{/with}} {{/each}}
This will output
<p> foo </p> <p> boo </p> <p> bar </p> <p> far </p>
The reason eval
and exec
are so dangerous is that the default compile
function will generate bytecode for any valid python expression, and the default eval
or exec
will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.
Instead, you can easily create a simple eval
function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.
c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]
The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d
, which is the bytecode for LOAD_CONST
, followed by the number of the constant to load (usually the last one in the list), followed by S
, which is the bytecode for RETURN_VALUE
. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).
This also opens the door to some more sophisticated input formats. For example:
stringExp = "1 + cos(2)"
This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS)
or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION
only allow functions in a 'safe' list.
from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator
globs = {'sin':sin, 'cos':cos}
safe = globs.values()
stack = LifoQueue()
class BINARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get(),stack.get()))
class UNARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get()))
def CALL_FUNCTION(context, arg):
argc = arg[0]+arg[1]*256
args = [stack.get() for i in range(argc)]
func = stack.get()
if func not in safe:
raise TypeError("Function %r now allowed"%func)
stack.put(func(*args))
def LOAD_CONST(context, arg):
cons = arg[0]+arg[1]*256
stack.put(context['code'].co_consts[cons])
def LOAD_NAME(context, arg):
name_num = arg[0]+arg[1]*256
name = context['code'].co_names[name_num]
if name in context['locals']:
stack.put(context['locals'][name])
else:
stack.put(context['globals'][name])
def RETURN_VALUE(context):
return stack.get()
opfuncs = {
opmap['BINARY_ADD']: BINARY(operator.add),
opmap['UNARY_INVERT']: UNARY(operator.invert),
opmap['CALL_FUNCTION']: CALL_FUNCTION,
opmap['LOAD_CONST']: LOAD_CONST,
opmap['LOAD_NAME']: LOAD_NAME
opmap['RETURN_VALUE']: RETURN_VALUE,
}
def VMeval(c):
context = dict(locals={}, globals=globs, code=c)
bci = iter(c.co_code)
for bytecode in bci:
func = opfuncs[ord(bytecode)]
if func.func_code.co_argcount==1:
ret = func(context)
else:
args = ord(bci.next()), ord(bci.next())
ret = func(context, args)
if ret:
return ret
def evaluate(expr):
return VMeval(compile(expr, 'userinput', 'eval'))
Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST
and a couple others would allow for input like 'x=5;return x+x
or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto
bytecodes, which means changing from a for
iterator to while
and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER
being the most obvious).
While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile
take anything arbitrarily complicated and reduces it to a sequence of simple instructions).
var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for(var x in parsed){
arr.push(parsed[x]);
}
Hope this is what you're after!
This example has a number of different aspects to it. I will mention a couple of points that I don't think have been explicitly covered elsewhere.
Protecting the secret in transit
The first thing to note is that accessing the dropbox API using their app authentication mechanism requires you to transmit your key and secret. The connection is HTTPS which means that you can't intercept the traffic without knowing the TLS certificate. This is to prevent a person intercepting and reading the packets on their journey from the mobile device to the server. For normal users it is a really good way of ensuring the privacy of their traffic.
What it is not good at, is preventing a malicious person downloading the app and inspecting the traffic. It is really easy to use a man-in-the-middle proxy for all traffic into and out of a mobile device. It would require no disassembly or reverse engineering of code to extract the app key and secret in this case due to the nature of the Dropbox API.
You could do pinning which checks that the TLS certificate you receive from the server is the one you expect. This adds a check to the client and makes it more difficult to intercept the traffic. This would make it harder to inspect the traffic in flight, but the pinning check happens in the client, so it would likely still be possible to disable the pinning test. It does make it harder though.
Protecting the secret at rest
As a first step, using something like proguard will help to make it less obvious where any secrets are held. You could also use the NDK to store the key and secret and send requests directly, which would greatly reduce the number of people with the appropriate skills to extract the information. Further obfuscation can be achieved by not storing the values directly in memory for any length of time, you can encrypt them and decrypt them just before use as suggested by another answer.
More advanced options
If you are now paranoid about putting the secret anywhere in your app, and you have time and money to invest in more comprehensive solutions, then you might consider storing the credentials on your servers (presuming you have any). This would increase the latency of any calls to the API, as it will have to communicate via your server, and might increase the costs of running your service due to increased data throughput.
You then have to decide how best to communicate with your servers to ensure they are protected. This is important to prevent all of the same problems coming up again with your internal API. The best rule of thumb I can give is to not transmit any secret directly because of the man-in-the-middle threat. Instead you can sign the traffic using your secret and verify the integrity of any requests that come to your server. One standard way of doing this is to compute an HMAC of the message keyed on a secret. I work at a company that has a security product that also operates in this field which is why this sort of stuff interests me. In fact, here is a blog article from one of my colleagues that goes over most of this.
How much should I do?
With any security advice like this you need to make a cost/benefit decision about how hard you want to make it for someone to break in. If you are a bank protecting millions of customers your budget is totally different to someone supporting an app in their spare time. It is virtually impossible to prevent someone from breaking your security, but in practice few people need all of the bells and whistles and with some basic precautions you can get a long way.
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.
I find it better and easier than downloading and pasting DLLs.
Its just like creating a WAR
file of your project, you can do it in several ways (from Eclipse, command line, maven).
If you want to do from command line, the command is
jar -cvf my_web_app.war *
Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)
<context:component-scan base-package="x.y.z"/>
will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.
Timezones. You have to deal with them, by using getTimezoneOffset()
if you want your visitors from around the wolrd to get the same time.
Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.
var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var eventTime = new Date();
eventTime.setTime(366549200);
var Offset = new Date(eventTime.getTimezoneOffset()*60000)
var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
I spent sometime looking for best practice that make sense and found the following which worked perfected for me. I hope this will save you sometime.
Using Config file (for example an asp.net website) https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/
or on your own server https://www.sslshopper.com/iis7-redirect-http-to-https.html
[SHORT ANSWER] Simply The code below goes inside
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP/S to HTTPS Redirect" enabled="true"
stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAny">
<add input="{SERVER_PORT_SECURE}" pattern="^0$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}"
redirectType="Permanent" />
</rule>
</rules>
</rewrite>
you can see the solution on http://jsfiddle.net/CBQCA/1/
OR
<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
<tr style="height: 25%;">
<td>Region</td>
</tr>
<tr style="height: 75%;">
<td>100.00%</td>
</tr>
</table>?
I removed the font size, to show that columns are expanded.
I added border:1px solid
just to make sure table is expanded. you can remove it.
After changing the ID it android.R.id.custom, I needed to add the following to get the View to display:
((View) f1.getParent()).setVisibility(View.VISIBLE);
However, this caused the new View to render in a big parent view with no background, breaking the dialog box in two parts (text and buttons, with the new View in between). I finally got the effect that I wanted by inserting my View next to the message:
LinearLayout f1 = (LinearLayout)findViewById(android.R.id.message).getParent().getParent();
I found this solution by exploring the View tree with View.getParent() and View.getChildAt(int). Not really happy about either, though. None of this is in the Android docs and if they ever change the structure of the AlertDialog, this might break.
You can use basic css to achieve smooth scroll
html {
scroll-behavior: smooth;
}
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:
ps -o pid -C bash
EDIT: Dependening on the sort of output you expect, pgrep
would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:
pgrep bash
... is syntax for variadic arguments.
I think it is implemented by the complier using slice ([]Type)
, just like the function append :
func append(slice []Type, elems ...Type) []Type
when you use "elems" in "append", actually it is a slice([]type).
So "a = append(a[:0], a[1:]...)
" means "a = append(a[0:0], a[1:])
"
a[0:0]
is a slice which has nothing
a[1:]
is "Hello2 Hello3"
This is how it works
It's a convention so the *nix shell knows what kind of interpreter to run.
For example, older flavors of ATT defaulted to sh (the Bourne shell), while older versions of BSD defaulted to csh (the C shell).
Even today (where most systems run bash, the "Bourne Again Shell"), scripts can be in bash, python, perl, ruby, PHP, etc, etc. For example, you might see #!/bin/perl
or #!/bin/perl5
.
PS:
The exclamation mark (!
) is affectionately called "bang". The shell comment symbol (#
) is sometimes called "hash".
PPS:
Remember - under *nix, associating a suffix with a file type is merely a convention, not a "rule". An executable can be a binary program, any one of a million script types and other things as well. Hence the need for #!/bin/bash
.
Just restating what Tomasz said.
There are many examples of FOO__in=...
style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:
users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])
# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])
The double underscore (__) syntax is used all over the place when working with querysets.
Works like a charm!
.imageClass {
-webkit-filter: drop-shadow(12px 12px 7px rgba(0,0,0,0.5));
}
Voila! That's it! Obviously this won't work in ie, but who cares...
@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "index.html");
}
}
You can assign the DataFrame
to a filtered version of itself:
df = df[df.score > 50]
This is faster than drop
:
%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In the your first journey in spring boot project I recommend you to start with Spring Starter Try this link here.
It will auto generate the project structure for you like this.application.perperties it will be under /resources.
application.properties important change,
server.port = Your PORT(XXXX) by default=8080
server.servlet.context-path=/api (SpringBoot version 2.x.)
server.contextPath-path=/api (SpringBoot version < 2.x.)
Any way you can use application.yml in case you don't want to make redundancy properties setting.
Example
application.yml
server:
port: 8080
contextPath: /api
application.properties
server.port = 8080
server.contextPath = /api
try {
// THIS for POST+JSON
options.contentType = 'application/json';
options.type = 'POST';
options.data = JSON.stringify(options.data);
// OR THIS for GET+URL-encoded
//options.data = $.param(_.clone(options.data));
console.log('.fetch options = ', options);
collection.fetch(options);
} catch (excp) {
alert(excp);
}
when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.
git push origin master:demo
The only problem I have found was change user agent only
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary *dictionary = [NSDictionary
dictionaryWithObjectsAndKeys:
@"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; ja-jp) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
@"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}
Here are some ways to edit the text and the size of the box:
rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"
Example:
<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter
Text Here</textarea>
With Postgres 9.3+, just use the ->
operator. For example,
SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;
see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.
please use response.close()
to close to avoid "too many open files" error
for example:
r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
....
r.close()
var selected=[];
$('#multipleSelect :selected').each(function(){
selected[$(this).val()]=$(this).text();
});
console.log(selected);
Yet another approch to this problem. The selected array will have the indexes as the option values and the each array item will have the text as its value.
for example
<select id="multipleSelect" multiple="multiple">
<option value="abc">Text 1</option>
<option value="def">Text 2</option>
<option value="ghi">Text 3</option>
</select>
if say option 1 and 2 are selected.
the selected array will be :
selected['abc']=1;
selected['def']=2.
You can use this for the Width of your DataTemplate:
Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}"
Make sure your DataTemplate root has Margin="0" (you can use some panel as the root and set the Margin to the children of that root)
import csv, sqlite3
def _get_col_datatypes(fin):
dr = csv.DictReader(fin) # comma is default delimiter
fieldTypes = {}
for entry in dr:
feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]
if not feildslLeft: break # We're done
for field in feildslLeft:
data = entry[field]
# Need data to decide
if len(data) == 0:
continue
if data.isdigit():
fieldTypes[field] = "INTEGER"
else:
fieldTypes[field] = "TEXT"
# TODO: Currently there's no support for DATE in sqllite
if len(feildslLeft) > 0:
raise Exception("Failed to find all the columns data types - Maybe some are empty?")
return fieldTypes
def escapingGenerator(f):
for line in f:
yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")
def csvToDb(csvFile,dbFile,tablename, outputToFile = False):
# TODO: implement output to file
with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
dt = _get_col_datatypes(fin)
fin.seek(0)
reader = csv.DictReader(fin)
# Keep the order of the columns name just as in the CSV
fields = reader.fieldnames
cols = []
# Set field and type
for f in fields:
cols.append("\"%s\" %s" % (f, dt[f]))
# Generate create table statement:
stmt = "create table if not exists \"" + tablename + "\" (%s)" % ",".join(cols)
print(stmt)
con = sqlite3.connect(dbFile)
cur = con.cursor()
cur.execute(stmt)
fin.seek(0)
reader = csv.reader(escapingGenerator(fin))
# Generate insert statement:
stmt = "INSERT INTO \"" + tablename + "\" VALUES(%s);" % ','.join('?' * len(cols))
cur.executemany(stmt, reader)
con.commit()
con.close()
If you just want to tack something on by hand, then the sed
answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):
Using Perl:
perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt
N.B. while the >>
may look like an indication of redirection, it is just the file open mode, in this case "append".
You may also have to use it in onPause
or onDestroy
of Activity
Life Cycle:
//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
loginTask.cancel(true);
where loginTask
is object of your AsyncTask
Thank you.
You can fire chnage event by these methods:
First
$('#selectid').change(function () {
alert('This works');
});
Second
$(document).on('change', '#selectid', function() {
alert('This Works');
});
Third
$(document.body).on('change','#selectid',function(){
alert('This Works');
});
If this methods not working, check your jQuery working or not:
$(document).ready(function($) {
alert('Jquery Working');
});
Assuming that the items in your CheckedListBox are strings:
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if ((string)checkedListBox1.Items[i] == value)
{
checkedListBox1.SetItemChecked(i, true);
}
}
Or
int index = checkedListBox1.Items.IndexOf(value);
if (index >= 0)
{
checkedListBox1.SetItemChecked(index, true);
}
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor
I've created a stored function for this text comparison purpose:
CREATE OR REPLACE FUNCTION TextCompare(vOperand1 IN VARCHAR2, vOperator IN VARCHAR2, vOperand2 IN VARCHAR2) RETURN NUMBER DETERMINISTIC AS
BEGIN
IF vOperator = '=' THEN
RETURN CASE WHEN vOperand1 = vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '<>' THEN
RETURN CASE WHEN vOperand1 <> vOperand2 OR (vOperand1 IS NULL) <> (vOperand2 IS NULL) THEN 1 ELSE 0 END;
ELSIF vOperator = '<=' THEN
RETURN CASE WHEN vOperand1 <= vOperand2 OR vOperand1 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '>=' THEN
RETURN CASE WHEN vOperand1 >= vOperand2 OR vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '<' THEN
RETURN CASE WHEN vOperand1 < vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NOT NULL THEN 1 ELSE 0 END;
ELSIF vOperator = '>' THEN
RETURN CASE WHEN vOperand1 > vOperand2 OR vOperand1 IS NOT NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = 'LIKE' THEN
RETURN CASE WHEN vOperand1 LIKE vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
ELSIF vOperator = 'NOT LIKE' THEN
RETURN CASE WHEN vOperand1 NOT LIKE vOperand2 OR (vOperand1 IS NULL) <> (vOperand2 IS NULL) THEN 1 ELSE 0 END;
ELSE
RAISE VALUE_ERROR;
END IF;
END;
In example:
SELECT * FROM MyTable WHERE TextCompare(MyTable.a, '>=', MyTable.b) = 1;
This might be a little late, but you need to create a singleton class that returns the custom typeface to avoid memory leaks.
TypeFace class:
public class OpenSans {
private static OpenSans instance;
private static Typeface typeface;
public static OpenSans getInstance(Context context) {
synchronized (OpenSans.class) {
if (instance == null) {
instance = new OpenSans();
typeface = Typeface.createFromAsset(context.getResources().getAssets(), "open_sans.ttf");
}
return instance;
}
}
public Typeface getTypeFace() {
return typeface;
}
}
Custom TextView:
public class NativelyCustomTextView extends TextView {
public NativelyCustomTextView(Context context) {
super(context);
setTypeface(OpenSans.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(OpenSans.getInstance(context).getTypeFace());
}
public NativelyCustomTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setTypeface(OpenSans.getInstance(context).getTypeFace());
}
}
By xml:
<com.yourpackage.views.NativelyCustomTextView
android:id="@+id/natively_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:text="@string/natively"
android:textSize="30sp" />
Programmatically:
TextView programmaticallyTextView = (TextView)
findViewById(R.id.programmatically_text_view);
programmaticallyTextView.setTypeface(OpenSans.getInstance(this)
.getTypeFace());
object-fit
property does the magic. On JsFiddle.
CSS
.image {
width: 160px;
height: 160px;
}
.object-fit_fill {
object-fit: fill
}
.object-fit_contain {
object-fit: contain
}
.object-fit_cover {
object-fit: cover
}
.object-fit_none {
object-fit: none
}
.object-fit_scale-down {
object-fit: scale-down
}
HTML
<div class="original-image">
<p>original image</p>
<img src="http://lorempixel.com/500/200">
</div>
<div class="image">
<p>object-fit: fill</p>
<img class="object-fit_fill" src="http://lorempixel.com/500/200">
</div>
<div class="image">
<p>object-fit: contain</p>
<img class="object-fit_contain" src="http://lorempixel.com/500/200">
</div>
<div class="image">
<p>object-fit: cover</p>
<img class="object-fit_cover" src="http://lorempixel.com/500/200">
</div>
<div class="image">
<p>object-fit: none</p>
<img class="object-fit_none" src="http://lorempixel.com/500/200">
</div>
<div class="image">
<p>object-fit: scale-down</p>
<img class="object-fit_scale-down" src="http://lorempixel.com/500/200">
</div>
Result
First, you need to have a clear understanding of scope
and behaviour of this
keyword in the context of scope
.
this
& scope
:
there are two types of scope in javascript. They are :
1) Global Scope
2) Function Scope
in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this
keyword in global scope refers to the window object.this
inside function also refers to the window object.So this
will always refer to the window until we find a way to manipulate this
to indicate a context of our own choosing.
--------------------------------------------------------------------------------
- -
- Global Scope -
- ( globally "this" refers to window object) -
- -
- function outer_function(callback){ -
- -
- // outer function scope -
- // inside outer function"this" keyword refers to window object - -
- callback() // "this" inside callback also refers window object -
- } -
- -
- function callback_function(){ -
- -
- // function to be passed as callback -
- -
- // here "THIS" refers to window object also -
- -
- } -
- -
- outer_function(callback_function) -
- // invoke with callback -
--------------------------------------------------------------------------------
Different ways to manipulate this
inside callback functions:
Here I have a constructor function called Person. It has a property called name
and four method called sayNameVersion1
,sayNameVersion2
,sayNameVersion3
,sayNameVersion4
. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.
function Person(name){
this.name = name
this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}
this.sayNameVersion3 = function(callback){
callback.call(this)
}
this.sayNameVersion4 = function(callback){
callback.apply(this)
}
}
function niceCallback(){
// function to be used as callback
var parentObject = this
console.log(parentObject)
}
Now let's create an instance from person constructor and invoke different versions of sayNameVersionX
( X refers to 1,2,3,4 ) method with niceCallback
to see how many ways we can manipulate the this
inside callback to refer to the person
instance.
var p1 = new Person('zami') // create an instance of Person constructor
What bind do is to create a new function with the this
keyword set to the provided value.
sayNameVersion1
and sayNameVersion2
use bind to manipulate this
of the callback function.
this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}
first one bind this
with callback inside the method itself.And for the second one callback is passed with the object bound to it.
p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method
p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback
The first argument
of the call
method is used as this
inside the function that is invoked with call
attached to it.
sayNameVersion3
uses call
to manipulate the this
to refer to the person object that we created, instead of the window object.
this.sayNameVersion3 = function(callback){
callback.call(this)
}
and it is called like the following :
p1.sayNameVersion3(niceCallback)
Similar to call
, first argument of apply
refers to the object that will be indicated by this
keyword.
sayNameVersion4
uses apply
to manipulate this
to refer to person object
this.sayNameVersion4 = function(callback){
callback.apply(this)
}
and it is called like the following.Simply the callback is passed,
p1.sayNameVersion4(niceCallback)
This may already be an answer but you could use random.shuffle
. Example:
import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)
I think you're using the CodeIgniter URI routing wrong: http://ellislab.com/codeigniter%20/user-guide/general/routing.html
Basically if you had a Products_controller with a method called delete($id)
and the url you created was of the form http://localhost/designs2/index.php/products_controller/delete/4
, the delete function would receive the $id
as a parameter.
Using what you have there I think you can get the id by using $this->input->get('product_id);
adb shell pm list packages
will give you a list of all installed package names.
You can then use dumpsys | grep -A18 "Package \[my.package\]"
to grab the package information such as version identifiers etc
I normally just run git mergetool
and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.
If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:
yes d | git mergetool -- the/subdirectory
The d
is provided to choose deleting each file. You can also use m
to keep the modified file. Taken from the prompt you see when you run mergetool
:
Use (m)odified or (d)eleted file, or (a)bort?
There are two ways:
If you are patient (requires Ubuntu corral pc and Android SDK and some heavy terminal work to get it all set up). See Using the 3.0 SDK without paying for the priviledge.
If you are immoral (requires Mac OS X Leopard and virtualization, both only obtainable through great expense or pirating) - remove space from the following link. htt p://iphonewo rld. codinghut.com /2009/07/using-the-3-0-sdk-without-paying-for-the-priviledge/
I use the Ubuntu method myself.
You can dynamically set the has-error css class (assuming you're using bootstrap) using ng-class and a property on the scope of the associated controller:
plunkr: http://plnkr.co/edit/HYDlaTNThZE02VqXrUCH?p=info
HTML:
<div ng-class="{'has-error': badEmailAddress}">
<input type="email" class="form-control" id="email" name="email"
ng-model="email"
ng-blur="emailBlurred(email.$valid)">
</div>
Controller:
$scope.badEmailAddress = false;
$scope.emailBlurred = function (isValid) {
$scope.badEmailAddress = !isValid;
};
For me, it worked very simply. At first, I made an empty data.frame
, then in each iteration I added one column to it. Here is my code:
df <- data.frame(modelForOneIteration)
for(i in 1:10){
model <- # some processing
df[,i] = model
}
This is not totally an answer to your question, but is related. I thought eclipse stopped showing red/yellow flags next to files in my project. The solution was very simple - I was looking at the Navigator tab (which doesn't show error/warning flags) instead of the Package Explorer tab.
You can use the TextView for the same purpose, But if you want to use the same with the ImageView then you have to create a class and extends the ImageView then use onDraw() method to paint the text on to the canvas. for more details visit to http://developer.android.com/reference/android/graphics/Canvas.html
This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.
topleft {
top: 0%;
left: 0%;
}
bottomright {
top: 100%;
left: 100%;
-webkit-transform: translate(-100%,-100%);
}
1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.
android {
...
defaultConfig {
multiDexEnabled true
...
}
}
dependencies {
// add dependency
implementation 'com.android.support:multidex:1.0.1'
}
2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
.
.
.
.
.
</application>
3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.
public class MyApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]
Hopefully, It works for you.
For Laravel 8 you can also use
Route::redirect('/here', '/there');
//or
Route::permanentRedirect('/here', '/there');
This also works with external URLs
Nested Depth for BSON Documents: MongoDB supports no more than 100 levels of nesting for BSON documents.
you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.
Then you controller is probably like this:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
@RequestParam Map<String, String> name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
...
PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
...
list = service.getPatient(patientProfileDto);
return list;
}
The problem occurred because of wrong table type.MyISAM is the only type of table that Mysql supports for Full-text indexes.
To correct this error run following sql.
CREATE TABLE gamemech_chat (
id bigint(20) unsigned NOT NULL auto_increment,
from_userid varchar(50) NOT NULL default '0',
to_userid varchar(50) NOT NULL default '0',
text text NOT NULL,
systemtext text NOT NULL,
timestamp datetime NOT NULL default '0000-00-00 00:00:00',
chatroom bigint(20) NOT NULL default '0',
PRIMARY KEY (id),
KEY from_userid (from_userid),
FULLTEXT KEY from_userid_2 (from_userid),
KEY chatroom (chatroom),
KEY timestamp (timestamp)
) ENGINE=MyISAM;
An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.